Home » Java » Java stream question, mapToInt and average method

Java stream question, mapToInt and average method

Posted by: admin December 28, 2021 Leave a comment


Why can I call average() method on one but not on the other? Shouldn’t they be equivalent?

example 1 – works

List<String> stringList = new ArrayList<>();
// String array ("2","4", "6"
averageValue = stringList.stream()
                .mapToInt(s -> Integer.valueOf(s))

example 2 – doesn’t compile (deleted mapToInt call because already passing Integer stream)

List<Integer> IntegerList = new ArrayList<>();

averageValue = IntegerList.stream()

Question, is why do I need to call mapToInt method when Im already passing it a stream of Integers?


There are two different types: a Stream<Integer> and an IntStream.

Java’s generics can’t have methods that only apply on some generics. For example, it couldn’t have Stream<Integer>.average() and not also have Stream<PersonName>.average(), even though the average person name doesn’t make sense.

Therefore, Stream has a mapToInt method that converts it into an IntStream, which then provides the average() method.


IntStream provides average() method, so to use it you need to convert Stream<Integer> to IntStream by using mapToInt method.