【问题标题】:Is there any way to reduce some code noise using java stream?有没有办法使用java流来减少一些代码噪音?
【发布时间】:2020-01-29 04:01:39
【问题描述】:

我有两个班级:

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;

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

【问题讨论】:

  • 是的。您是否尝试过阅读 Stream 的 javadoc?或者解释流如何工作的许多教程之一,以及你可以用它们做什么(比如 map() 和 collect())?通过阅读文档,您将学到很多
  • 还有related
  • 考虑map2.forEach((k, v) -&gt; map.put(new Cat(k.getId(), k.getName()), v)),但也考虑放弃地图并将location添加到Animal,因为使用地图似乎意味着每个动物都有一个位置。

标签: java java-stream


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可以将toMap() 收集器与合并重载一起使用:

    Map<Cat, Location> map =
    map2.entrySet()
        .stream()
        .collect(toMap(e-> new Cat(e.getKey().getId()), entry.getKey().getName(), 
                       Entry::getValue, (a,b)->b ));
    

    或者没有流可能更简单:

    Map<Cat, Location> map = new HashMap<>();
    map2.forEach( (k,v) -> map.put(new Cat(k.getId(), k.getName()), v) );
    

    【讨论】:

      猜你喜欢
      • 2021-12-06
      • 2011-11-23
      • 1970-01-01
      • 2016-01-04
      • 1970-01-01
      • 2014-02-25
      • 2013-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多