June 2018
Beginner
722 pages
18h 47m
English
If you need to calculate a sum or an average of the values of numeric stream elements, the only requirement for the stream is that it should not be infinite. Otherwise, the calculation never finishes:
int sum = IntStream.empty().sum();System.out.println(sum); //prints: 0sum = IntStream.range(1, 3).sum();System.out.println(sum); //prints: 3double av = IntStream.empty().average().orElse(0);System.out.println(av); //prints: 0.0av = IntStream.range(1, 3).average().orElse(0);System.out.println(av); //prints: 1.5long suml = LongStream.range(1, 3).sum();System.out.println(suml); //prints: 3double avl = LongStream.range(1, 3).average().orElse(0);System.out.println(avl); //prints: 1.5double sumd = DoubleStream.of(1, 2).sum();
Read now
Unlock full access