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]
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With