Java - Lambda filter criteria, to ignore adding to map

99封情书 提交于 2019-12-08 02:45:15

问题


I have a map of the format (reference to Finding average using Lambda (Double stored as String))

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))));

I would like to ignore the ignore the entire country mapping even if one of them is newIndex value for that country is empty?


回答1:


Since Collectors.groupingBy does not allow to skip groups, you either have to analyze the filtering condition in advance so you can filter before performing groupBy or filter the map afterwards (I ignore the third option, implement your own groupingBy collector.

  1. Analyze in advance:

    Map<String, Boolean> hasEmpty=mapOfIndicators.values().stream()
        .flatMap(Collection::stream)
        .collect(Collectors.groupingBy(ObjectDTO::getCountryName,
            Collectors.mapping(o->o.getNewIndex().isEmpty(),
                Collectors.reducing(false, Boolean::logicalOr))));
    Map<String, Double> averages=mapOfIndicators.values().stream()
        .flatMap(Collection::stream)
        .filter(objectDTO -> !hasEmpty.get(objectDTO.getCountryName()))
        .collect(Collectors.groupingBy(ObjectDTO::getCountryName,
            Collectors.mapping(ObjectDTO::getNewIndex,
                Collectors.averagingDouble(Double::parseDouble))));
    
  2. Filter the result:

    Map<String, Double> averages=mapOfIndicators.values().stream()
        .flatMap(Collection::stream)
        .collect(Collectors.collectingAndThen(
            Collectors.groupingBy(ObjectDTO::getCountryName,
                Collectors.mapping(ObjectDTO::getNewIndex, Collectors.averagingDouble(
                    s->s.isEmpty()? Double.NaN: Double.parseDouble(s)))),
            m->{ m.values().removeIf(d->Double.isNaN(d)); return m; }));
    


来源:https://stackoverflow.com/questions/25869821/java-lambda-filter-criteria-to-ignore-adding-to-map

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