Is there a Java stream method for finding the average value for a specific field property which is inside a list of Objects?

I have a list which stores objects from the class Vehicle:

List< Vehicle > vehicles= new ArrayList<>();

The class vehicle has property "type"(of type String) and property "horsepower"(of type Double).

I find the average car horse power like this:

double averageCarHorsePower = average(vehicles.stream.filter(e -> e.getType().equals("car")).collect(Collectors.toList()));

private static double average (List< Vehicle > vehicles) { `
    if (vehicles.size() == 0) 
        return 0.0;
    }
    double sum = 0;
    for (Vehicle vehicle : vehicles) {
        sum += vehicle.getHorsepower();
    }
    return sum / vehicles.size();

But I want to find the average in one line without using a method.

I am asking this kind of question, because with Array stream it is simply:

double average = Array.stream(vehiclesHorsepower).mapToDouble(Double::doubleValue().average();

Upvotes: 0

Views: 2787

Answers (1)

Michael Mesfin
Michael Mesfin

Reputation: 556

Collectors.averagingDouble Calculates the average value of a Double property of the items in the stream.

double averageCarHorsePower = vehicles.stream()
         .filter(v -> v.getType().equals("cars"))
         .collect(Collectors.averagingDouble(Vehicle::getHorsePower));

Upvotes: 3

Related Questions