【问题标题】:How to refactor Java 7 as Java 8 when comparing a map and list [closed]比较地图和列表时如何将 Java 7 重构为 Java 8 [关闭]
【发布时间】:2018-04-19 22:19:35
【问题描述】:

我想重构以下代码使其更具可读性。有没有办法使用流和 lambdas 让代码更具可读性,或者让代码保持原样有意义吗?

List<Data> data = ...;
Map<String, Task> tasks = ...;
for (Data datum : data) {
    String compKey = datum.getCompKey();
    for (Map.Entry<String, Task> taskEntry : tasks.entrySet()) {
        String taskKey = taskEntry.getKey();
        Task task = taskEntry.getValue();
        if (taskKey != null && task != null) {
            String subKey = Joiner.on(".").useForNull("null").join(Arrays.copyOfRange(taskKey.split("\\."), 0, 3));
            if (compKey.equals(subKey)) {
                task.setVal1(datum.getVal1());
                task.setVal2(datum.getVal2());
                task.setVal3(datum.getVal3());                       
                break;
            }
        }
    }
}

【问题讨论】:

    标签: java dictionary java-8 refactoring java-stream


    【解决方案1】:

    这个怎么样?

    tasks.forEach((key, task) -> {
        if (key != null && task != null) {
            key = String.join(".", Arrays.asList(key.split("\\.")).subList(0, 3));
            data.stream()
                .filter(d -> d.getCompKey().equals(key))
                .findAny()
                .ifPresent(d -> {
                    task.setVal1(d.getVal1());
                    task.setVal2(d.getVal2());
                    task.setVal3(d.getVal3());
                });
        }
    });
    

    【讨论】:

      【解决方案2】:

      我不会说这比您的代码更具可读性,但它表明好的 ol' for 循环仍然足够:

      List<Data> data = ...;
      Map<String, Task> tasks = ...;
      
      UnaryOperator<String> function = s -> {
          return Joiner.on(".")
                       .useForNull("null")
                       .join(Arrays.copyOfRange(s.split("\\."), 0, 3));
      };
      
      data.forEach(datum -> {
          final String compKey = datum.getCompKey();
      
          tasks.entrySet()
               .stream()
               .filter(e -> e.getKey() != null && e.getValue() != null)
               .filter(e -> compKey.equals(function.apply(e.getKey())))
               .findFirst()
               .map(Map.Entry::getValue)
               .ifPresent(task -> {
                   task.setVal1(datum.getVal1());
                   task.setVal2(datum.getVal2());
                   task.setVal3(datum.getVal3());
               });
      });
      

      【讨论】:

        猜你喜欢
        • 2018-05-30
        • 1970-01-01
        • 2017-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-24
        相关资源
        最近更新 更多