Print result of IntStream average

Michael Fogarty :

I'm currently learning about streams and am using the .average function to figure out the average of some integers that are input using the scanner. The problem I'm running into is how to format the output so that it doesn't say optional double.

import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ClassAverage {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    List<Integer> grades = new ArrayList<Integer>();

    while (scan.hasNextInt()) {
        grades.add(scan.nextInt());

        if (scan.equals("end")) {
            {
                break;
            }

        }
        grades.forEach(System.out::println);

    }

    System.out.println("" + grades.stream()
            .mapToInt(Integer::intValue)
            .average());

}
}

This is the output I'm getting

 OptionalDouble[88.0]
Andrew Tobilko :

average() returns an OptionalDouble object, not a double.

If you've got a single action to perform over the result, like printing it, you could use ifPresent​(DoubleConsumer):

grades.stream()
        .mapToInt(Integer::intValue)
        .average()
        .ifPresent(System.out::println);

Otherwise,

OptionalDouble optionalAverage = grades.stream()
        .mapToInt(Integer::intValue)
        .average();

if (optionalAverage.isPresent()) {
    double average = optionalAverage.getAsDouble();
    System.out.println(average);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=68371&siteId=1
Recommended