0

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?

3
  • 3
    Change the type of anotherLinkMap to Map or use the four argument version of toMap. Commented Apr 9, 2020 at 7:54
  • are you looking to Map<String, Link> collect = linkMap.values().stream() .collect(Collectors.toMap(Link::getLink, l -> l));? Commented Apr 9, 2020 at 8:02
  • @michalk seems, it helped, thanks. Commented Apr 9, 2020 at 8:05

1 Answer 1

2

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.