Search code examples
javahashmapjava-streamcollectors

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


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?


Solution

  • 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));