Java 8 Streams Java Java API
Interface:
java.util.stream.IntStream
Method:
OptionalDouble average()
This terminal operation returns an OptionalDouble describing the arithmetic mean of elements of this stream, or an empty optional if this stream is empty. This is a special case of reduction.
Examples
package com.logicbig.example.intstream;
import java.util.OptionalDouble; import java.util.stream.IntStream;
public class AverageExample {
public static void main(String... args) { IntStream intStream = IntStream.of(1, 2, 3, 2, 5, 4); OptionalDouble average = intStream.average(); System.out.println(average.orElse(-1)); } }
Output2.8333333333333335
package com.logicbig.example.intstream;
import java.util.stream.IntStream;
public class AverageExample2 {
public static void main(String... args) { IntStream intStream = IntStream.of(1, 2, 3, 2, 5, 4); double average = intStream.average().orElseThrow(RuntimeException::new); System.out.println(average); } }
Output2.8333333333333335
|
|