英文:
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>
不存在类型变量K,U的实例,使得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<Link> linkStream = linkMap.values().stream();
HashMap<String, Link> anotherLinkMap = linkStream.collect(Collectors.toMap(l -> l.getLink(), l -> l));
But the compiler says:
Required type:
HashMap<String, Link>
Provided:
Map<Object, Object>
no instance(s) of type variable(s) K, U exist so that Map<K, U> conforms to HashMap<String, Link>
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<String,Link>
,或者使用toMap
方法的四个参数版本:
HashMap<String, Link> anotherLinkMap = linkStream.collect(Collectors.toMap(Link::getLink, link -> link, (link, link2) -> link, HashMap::new));
英文:
The collector you are using returns some implementation of Map
so either you change the type of anotherLinkMap
to Map<String,Link>
or use the four argument version of the toMap
method :
HashMap<String, Link> anotherLinkMap = linkStream.collect(Collectors.toMap(Link::getLink, link -> link, (link, link2) -> link, HashMap::new));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论