Java – 使用属性作为键从流创建 HashMap

huangapple go评论90阅读模式
英文:

Java - create HashMap from stream using a property as a key

问题

我有一个HashMap,其中id是键,entity是值。我需要创建一个新的HashMap,以一个entity的属性作为键,整个entity作为值。所以我写了:

Stream<Link> linkStream = linkMap.values().stream();
HashMap<String, Link> anotherLinkMap = linkStream.collect(Collectors.toMap(l -> l.getLink(), l -> l));

但编译器显示:

所需类型
HashMap<String, Link>
提供类型
Map<Object, Object>
不存在类型变量KU的实例使得Map<K, U>符合HashMap<String, Link>

是的,使用for循环很容易写出来,但我想使用流(Stream)。我在这里做错了什么?

英文:

I have a HashMap where id is a key and entity is a value. I need to create a new HashMap with one entity's property as a key and entire entity remains a value. So I wrote:

Stream&lt;Link&gt; linkStream = linkMap.values().stream();
HashMap&lt;String, Link&gt; anotherLinkMap = linkStream.collect(Collectors.toMap(l -&gt; l.getLink(), l -&gt; l));

But the compiler says:

Required type:
HashMap&lt;String, Link&gt;
Provided:
Map&lt;Object, Object&gt;
no instance(s) of type variable(s) K, U exist so that Map&lt;K, U&gt; conforms to HashMap&lt;String, Link&gt;

Yes, it is easy to write it using for loop, but I would like to use stream. What am I doing wrong here?

答案1

得分: 2

收集器您正在使用的返回Map的某些实现,因此您可以将anotherLinkMap的类型更改为Map&lt;String,Link&gt;,或者使用toMap方法的四个参数版本:

HashMap&lt;String, Link&gt; anotherLinkMap = linkStream.collect(Collectors.toMap(Link::getLink, link -&gt; link, (link, link2) -&gt; link, HashMap::new));
英文:

The collector you are using returns some implementation of Map so either you change the type of anotherLinkMap to Map&lt;String,Link&gt; or use the four argument version of the toMap method :

HashMap&lt;String, Link&gt; anotherLinkMap = linkStream.collect(Collectors.toMap(Link::getLink, link -&gt; link, (link, link2) -&gt; link, HashMap::new));

huangapple
  • 本文由 发表于 2020年4月9日 15:49:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/61116304.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定