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

Questions:

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<>();
    stringList.add("2");
    stringList.add("4");
    stringList.add("6");
// String array ("2","4", "6"
averageValue = stringList.stream()
                .mapToInt(s -> Integer.valueOf(s))
                .average()
                .getAsDouble();   

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

List<Integer> IntegerList = new ArrayList<>();
        IntegerList.add(2);
        IntegerList.add(4);
        IntegerList.add(6);

averageValue = IntegerList.stream()
                    .average()
                    .getAsDouble();  

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

Answers:

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.