Finding average using Lambda (Double stored as String)

左心房为你撑大大i 提交于 2019-12-04 18:07:32

Not tested, but should do the trick (or at least guide you towards the solution):

Map<String, Double> averageByCountryName = 
    map.values()
       .stream()
       .flatMap(list -> list.stream())
       .filter(objectDTO -> !objectDTO.getNewIndex().isEmpty())
       .collect(Collectors.groupingBy(
            ObjectDTO::getCountry,
            Collectors.averagingDouble(
                objectDTO -> Double.parseDouble(objectDTO.getNewIndex())));
Holger

If you want to calculate the average of the values and collect them in a Map having the same keys as the source map, you can do it this way:

Map<String, Double> averages=mapOfIndicators.entrySet().stream()
    .collect(Collectors.toMap(Map.Entry::getKey, e->e.getValue().stream()
       .map(ObjectDTO::getNewIndex).filter(str->!str.isEmpty())
       .mapToDouble(Double::parseDouble).average().orElse(Double.NaN)));

Since ObjectDTO.newIndex is declared private, I assumed that there is a method getNewIndex to get its value. I also provided the default value Double.NaN as behavior for the case that there are no non-empty Strings in the value list which was not specified in the question.


In the case you want to average over a different key as with your question now defined more precisely, the code may look like:

Map<String, Double> averages=mapOfIndicators.values().stream()
    .flatMap(Collection::stream)
    .filter(objectDTO -> !objectDTO.getNewIndex().isEmpty())
    .collect(Collectors.groupingBy(ObjectDTO::getCountryName,
        Collectors.mapping(ObjectDTO::getNewIndex,
            Collectors.averagingDouble(Double::parseDouble))));

Well, that’s similar to JB Nizet’s answer which got your intention right on the first guess…

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!