我刚刚开始研究Java8,为了try lambdas,我想我应该try 重写我最近写的一个非常简单的东西.我需要将一个字符串到列的映射转换为另一个字符串到列的映射,其中新映射中的列是第一个映射中的列的防御副本.列有一个复制构造函数.到目前为止,我得到的最接近的结果是:

    Map<String, Column> newColumnMap= new HashMap<>();
    originalColumnMap.entrySet().stream().forEach(x -> newColumnMap.put(x.getKey(), new Column(x.getValue())));

但我相信一定有更好的方法可以做到这一点,如果你能给我一些建议,我将不胜感激.

推荐答案

你可以用Collector:

import java.util.*;
import java.util.stream.Collectors;

public class Defensive {

  public static void main(String[] args) {
    Map<String, Column> original = new HashMap<>();
    original.put("foo", new Column());
    original.put("bar", new Column());

    Map<String, Column> copy = original.entrySet()
        .stream()
        .collect(Collectors.toMap(Map.Entry::getKey,
                                  e -> new Column(e.getValue())));

    System.out.println(original);
    System.out.println(copy);
  }

  static class Column {
    public Column() {}
    public Column(Column c) {}
  }
}

Java相关问答推荐

获取拦截器内部的IP地址

Java Streams在矩阵遍历中的性能影响

如何在返回bigint []值的子查询中使用any?

@ IdClass with @ Inheritance(策略= InheritanceType. SINGLE_TABLE)

springboot start loge change

R.id.main给我一个红色错误,无法解析MainActivity.java中的符号main

如何在运行时动态创建表(使用Java、JPA、SprringBoot)

在Spring Boot应用程序中导致";MediaTypeNotSupportdException&qot;的映像上载

通过移动一个类解决了潜在的StubbingProblem.它怎麽工作?

使用Spring和ActiveMQ的侦听器方法引发属性名称不能重复为空警告

Com.google.firebase.database.DatabaseException:无法将类型为java.lang.Boolean的值转换为字符串.这是关于什么的?

有没有更快的方法在N个容器中删除重复项?

使用OAuth 2.0资源服务器JWT时的授权(授权)问题

在处理2个映射表时,没有更多的数据可从套接字读取

何时调用密封层次 struct 的switch 中的默认情况

在Eclipse中可以使用外部字体吗?

为什么创建Java动态代理需要接口参数

如何使用jOOQ在PostgreSQL中从枚举类型生成Java枚举

using case default on switch语句返回;预览特征切换中的模式匹配仅在源级别20及以上的情况下可用;

如何使用Jackson读取以方括号开头的JSON?