Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print result of IntStream average

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]
like image 520
Michael Fogarty Avatar asked Sep 30 '18 22:09

Michael Fogarty


Video Answer


1 Answers

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);
}
like image 145
Andrew Tobilko Avatar answered Oct 27 '22 00:10

Andrew Tobilko