Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stream question, mapToInt and average method

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?

like image 539
Ratkhan Avatar asked Apr 05 '20 17:04

Ratkhan


People also ask

How average is calculated in stream in Java?

IntStream average() method in JavaThe average() method of the IntStream class in Java returns an OptionalDouble describing the arithmetic mean of elements of this stream, or an empty optional if this stream is empty. It gets the average of the elements of the stream.

What is the use of mapToInt in Java?

The mapToInt() method returns an IntStream consisting of the results of applying the given function to the elements of this stream. Here, the parameter mapper is the stateless function applied to each element.

How do you find the average of a list in Java 8?

The logic is very simple. First, we will initialize a variable sum to 0 that holds the sum of the list elements. Declare another element say average (avg), it holds the average of the list. We have created an instance of the ArrayList class and invoked the add() method to add the elements to the List.

What is IntStream in Java?

An IntStream interface extends the BaseStream interface in Java 8. It is a sequence of primitive int-value elements and a specialized stream for manipulating int values. We can also use the IntStream interface to iterate the elements of a collection in lambda expressions and method references.


Video Answer


2 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.

like image 140
Louis Wasserman Avatar answered Sep 28 '22 05:09

Louis Wasserman


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

like image 29
Eklavya Avatar answered Sep 28 '22 05:09

Eklavya