java - 有没有办法使用java流来减少一些代码噪音?
问题描述
我有两节课:
public class Cat
{
public Cat(UUID id, String name)
{
this.id = id;
this.name = name;
}
@Getter
UUID id;
@Getter
String name;
}
public class Animal
{
@Getter
UUID id;
@Getter
String name;
}
我有两张地图:
Map<Cat, Location> map = new HashMap<>();
Map<Animal, Location> map2 = new HashMap<>();
我需要轻松地将map2
数据转换为map
. 我能够使用以下代码做到这一点:
for (Entry<Animal, Location> entry : map2.entrySet())
{
UUID id = entry.getKey().getId();
String name = entry.getKey().getName();
Cat key = new Cat(id, name);
map.put(key, entry.getValue());
}
return map;
有没有更好的方法来做到这一点,或者我正在采取的方法好吗?
解决方案
您可以Collectors.toMap
用作:
Map<Cat, Location> map = map2.entrySet().stream()
.collect(Collectors.toMap(
entry -> new Cat(entry.getKey().getId(), entry.getKey().getName()),
Map.Entry::getValue,
(a, b) -> b));
推荐阅读
- java - 从另一个类调用函数?
- swift - 键盘未关闭
- r - 如何更改包装器(R)中函数的绘图参数
- java - 如果缓存为空 NPE 则进行改造
- gitlab - 如何在 Gitlab 中运行不会阻塞后续阶段的作业?
- javascript - 从jquery中动态生成的下拉按钮获取值
- rest - 将自定义构建的聊天机器人与 Skype 集成
- ruby-on-rails - 如何在另一个对象的回调中为对象指定方法
- abap - 如何将abap中的SELECT循环更改为字段符号
- python-3.x - PyTorch - Torchvision - BrokenPipeError:[Errno 32] 断管