Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform String Array to int Array with streams

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 Answers

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();
like image 93
Nicholas Kurian Avatar answered May 13 '26 02:05

Nicholas Kurian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!