Java 8 Stream : Map Sum values example using mapToInt

Stream : mapToInt method

mapToInt method is introduced in stream and its designed to transform a stream of object into intStream.

What is intStream ? 

IntStream is specialized stream that deals with primitve int value which can be more efficient than regular Stream<Integer>

Key Points :

1.What is purpose mapTOInt method ?

mapToInt is used to convert each element in stream to an int and its used to perform numeric operations like sum, average and find max and minimum element.

2. What is method signature of mapToInt method ?

mapToInt(ToIntFunction<? super T> mapper) : The method takes a functional interface ToIntFunction as input of type T and produces an int
int applyAsInt(T value) : This method is available in interface which is implemented by a lambda expression or method reference.

 List<String> words = Arrays.asList("apple", "banana", "cherry");
IntStream lengths = words.stream().mapToInt(String::length);
 

In below example, mapToInt(String::length) converts the stream of strings into an IntStream of their lengths, and then sum() adds up lengths to give the total.

List<String> words = Arrays.asList("apple", "banana", "cherry");

// Using mapToInt to get the length of each word and sum them
int totalLength = words.stream()
                       .mapToInt(String::length)
                       .sum();

System.out.println("Total length of all words: " + totalLength);