提问者:小点点

Java流-收集、转换和收集


我想获取地图的值,找到min值,并为地图的每个条目构造一个新的CodesWitMinValue实例。我希望使用Java11个流,我可以在多行中使用多个流(一个用于min值,一个用于转换)来实现这一点。是否可以使用java 11流和收集器在单行中实现?谢谢。

public static void main(String[] args) {
        Map<String, Integer> codesMap = getMockedCodesFromUpstream();
        var minValue = Collections.min(codesMap.values());
        var resultList = codesMap.entrySet().stream()
                .map(e -> new CodesWithMinValue(e.getKey(), e.getValue(), minValue))
                .collect(Collectors.toUnmodifiableList());

        //is it possible to combine above three lines using stream and collectors API, 
       //and also can't call getMockedCodesFromUpstream() more than once. getMockedCodesFromUpstream() is a mocked implementation for testing.
        //TODO: combine above three lines into a single line if possible
        System.out.println(resultList);
    }
    
    private static Map<String, Integer> getMockedCodesFromUpstream(){
        Map<String, Integer> codesMap = new HashMap<>();
        codesMap.put("CDXKF", 44);
        codesMap.put("GFDFS", 13);
        codesMap.put("KUSSS", 10);
        codesMap.put("EWSNK", 52);
        codesMap.put("IOLHF", 21);
        return codesMap;
    }

    private static class CodesWithMinValue{
        public final String code;
        public final int value;
        public final int minValue;

        public CodesWithMinValue(String code, int value, int minValue) {
            this.code = code;
            this.value = value;
            this.minValue = minValue;
        }

        @Override
        public String toString() {
            return "CodesWithMinValue{" +
                    "code='" + code + '\'' +
                    ", value=" + value +
                    ", minValue=" + minValue +
                    '}';
        }
    }

共1个答案

匿名用户

我觉得这可以通过重构和隐藏数据片段来简化,而不是过度使用收集器。

  private static BiFunction<Map<String, Integer>, Integer, List<MyNode>> getListOfMyNodeWithMinValue =
      (map, minValue) ->
          map.entrySet().stream()
              .map(entry -> new MyNode(entry.getKey(), entry.getValue(), minValue))
              .collect(Collectors.toList());

  public static Function<Map<String, Integer>, List<MyNode>> getMyNodes =
      map -> getListOfMyNodeWithMinValue.apply(map, Collections.min(map.values()));

之后可以将其用作MyNode。getMyNodes。应用(inputMap)。

忽略我的命名约定。只要输入我的感觉。希望你有这个想法。