首页 > 解决方案 > 有没有办法使用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;

有没有更好的方法来做到这一点,或者我正在采取的方法好吗?

标签: javajava-stream

解决方案


您可以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));

推荐阅读