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?
基础教程推荐
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
