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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With