简体   繁体   中英

Compute the Mean of a List<Double> in a HashMap in Java

Given a map from Names to lists of Numbers.

I'd like to compute the mean for each Name using the java 8 stream api.

Map<String, List<Double>> NameToQuaters = new HashMap<>();

Map<String, Double> NameToMean = ?

You need something like this :

Map<String, Double> nameToMean = nameToQuaters.entrySet()
        .stream()
        .collect(Collectors.toMap(
                // the key is the same
                Map.Entry::getKey,
                // for the value of the key, you can calculate the average like so
                e -> e.getValue().stream().mapToDouble(Double::doubleValue).average().getAsDouble())
        );
    }

Or you can create a method which make the average and return it back for example :

public Double average(List<Double> values) {
    return values.stream().mapToDouble(Double::doubleValue).average().getAsDouble();
}

then your code can be :

Map<String, Double> nameToMean = nameToQuaters.entrySet()
        .stream()
        .collect(Collectors.toMap(Map.Entry::getKey, e -> average(e.getValue())) );

This should do the trick:

Map<String, List<Double>> nameToQuaters = new HashMap<>();
//fill source map
Map<String, Double> nameToMean = new HashMap<>();
nameToQuaters.
    .forEach((key, value) -> nameToMean.put(key, value.stream().mapToDouble(a -> a).average().getAsDouble()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM