Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of the lengths of a string array using Java 8 streams

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?

like image 672
John Difool Avatar asked Mar 22 '18 20:03

John Difool


People also ask

How do you find the sum of an array using streams?

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() .

Does Java 8 support streams?

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.

What is stream () method in Java?

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.


Video Answer


2 Answers

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();
like image 158
fps Avatar answered Sep 28 '22 16:09

fps


Try this

Arrays.stream(text)
      .filter(Objects::nonNull)
      .mapToInt(String::length)
      .reduce(0,Integer::sum);
like image 34
Hadi J Avatar answered Sep 28 '22 15:09

Hadi J