9

I'm making a simple class that takes an array of Strings and returns an array of integers with the length of each string in them. I'm trying to use the Java 8 Stream API to do it.

public int[] findMostSimilar(String[] words) {

    return Arrays.stream(words).map(n -> n.length()).toArray();

}

But an error appears in the stream itself indicating

incompatible types, required: int[], found: java.lang.Object[].

Any ideas how to accomplish what I want?

1

2 Answers 2

20

First lets see why your attempt didn't work :

Arrays.stream(words).map(n -> n.length()).toArray(); 

The above statement returns Object[]. You could use .toArray(Integer[]::new); but then this would return Integer[]


Instead you can make use of mapToInt :

int[] array = Arrays.stream(words).mapToInt(String::length).toArray();
Sign up to request clarification or add additional context in comments.

Comments

1

This should work.

int[] ints = Arrays.stream(words).mapToInt(String::length).toArray();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.