【问题标题】:Java stream - collect, transform and collectJava 流 - 收集、转换和收集
【发布时间】:2021-03-18 08:26:18
【问题描述】:

我想获取地图的值并找到最小值并为地图的每个条目构造一个新的 CodesWithMinValue 实例。我希望使用 Java 11 流来实现这一点,我可以使用多行中的多个流来实现这一点(一个用于最小值,一个用于转换)。是否可以使用 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 +
                    '}';
        }
    }

【问题讨论】:

    标签: java java-stream java-11


    【解决方案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.apply(inputMap)

    忽略我的命名约定。随便输入我的感受。希望你明白了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-22
      • 1970-01-01
      • 1970-01-01
      • 2022-10-07
      • 2018-02-16
      • 1970-01-01
      相关资源
      最近更新 更多