EN
Java 8 - stream average
0 points
In this article, we would like to show you how to find stream average in Java 8.
Quick solution:
xxxxxxxxxx
1
// example stream
2
Stream<Integer> streamOfIntegers = Stream.of(1, 2, 3);
3
4
streamOfIntegers
5
.mapToDouble(x -> x)
6
.average()
7
.ifPresent(avg -> System.out.println("average = " + avg)); // 2.0
In this example, we use:
mapToInt()
- to map each element of the stream to int,average()
- to calculate the average element of the stream,ifPresent()
- to display the average if the value is present.
xxxxxxxxxx
1
import java.util.stream.Stream;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
// example stream
7
Stream<Integer> streamOfIntegers = Stream.of(1, 2, 3);
8
9
// find stream average
10
streamOfIntegers
11
.mapToInt(x -> x)
12
.average()
13
.ifPresent(avg -> System.out.println("average = " + avg));
14
}
15
}
Output:
xxxxxxxxxx
1
average = 2.0