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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With