In Java 8 how do I transform a Maplt;K,Vgt; to another Maplt;K,Vgt; using a lambda?(在 Java 8 中,我如何转换 Maplt;K,Vgt;到另一个地图lt;K,Vgt;使用 lambda?)
问题描述
我刚开始研究 Java 8 并尝试 lambda,我想我会尝试重写我最近写的一个非常简单的东西.我需要将字符串到列的映射转换为另一个字符串到列的映射,其中新映射中的列是第一个映射中列的防御性副本.Column 有一个复制构造函数.到目前为止,我得到的最接近的是:
I've just started looking at Java 8 and to try out lambdas I thought I'd try to rewrite a very simple thing I wrote recently. I need to turn a Map of String to Column into another Map of String to Column where the Column in the new Map is a defensive copy of the Column in the first Map. Column has a copy constructor. The closest I've got so far is:
Map<String, Column> newColumnMap= new HashMap<>();
originalColumnMap.entrySet().stream().forEach(x -> newColumnMap.put(x.getKey(), new Column(x.getValue())));
但我确信一定有更好的方法来做到这一点,我将不胜感激.
but I'm sure there must be a nicer way to do it and I'd be grateful for some advice.
推荐答案
你可以使用 收藏家:
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 8 中,我如何转换 Map<K,V>到另一个地图<K,V>使用 lambda?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Java 8 中,我如何转换 Map<K,V>到另一个地图<K,V>使用 lambda?


- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01