I've written this code that doesn't compile:
String[] text = {"hello", "bye"};
IntStream.of(Arrays.stream(text).map(String::length)).sum()
Do I need to convert the stream to an IntStream? And why do I get an error when I pass String::length
to the map()
function?
Using Stream.collect() The second method for calculating the sum of a list of integers is by using the collect() terminal operation: List<Integer> integers = Arrays. asList(1, 2, 3, 4, 5); Integer sum = integers. stream() .
Java 8 offers the possibility to create streams out of three primitive types: int, long and double. As Stream<T> is a generic interface, and there is no way to use primitives as a type parameter with generics, three new special interfaces were created: IntStream, LongStream, DoubleStream.
A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The features of Java stream are – A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
You should use Stream.mapToInt
in order to get an IntStream
instance:
String[] text = {"hello", "bye"};
int total = Arrays.stream(text).mapToInt(String::length).sum();
Try this
Arrays.stream(text)
.filter(Objects::nonNull)
.mapToInt(String::length)
.reduce(0,Integer::sum);
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