我有一个 HashMap,其中 id 是键,entity 是值。我需要创建一个新的 HashMap,其中一个实体的属性作为键,整个实体仍然是一个值。所以我写道:
Stream<Link> linkStream = linkMap.values().stream();
HashMap<String, Link> anotherLinkMap = linkStream.collect(Collectors.toMap(l -> l.getLink(), l -> l));
但是编译器说:
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>
是的,使用for
循环编写它很容易,但我想使用流。我在这里做错了什么?
最佳答案
您正在使用的收集器返回 Map
的一些实现所以要么你改变 anotherLinkMap
的类型至Map<String,Link>
或使用 toMap
的四个参数版本方法:
HashMap<String, Link> anotherLinkMap = linkStream.collect(Collectors.toMap(Link::getLink, link -> link, (link, link2) -> link, HashMap::new));
关于Java - 使用属性作为键从流创建 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61116304/