1

if I have something like this:

List<Person> fetchedPeople

and I want to stream through it and store it into a key-value map where key is the person ID and value is the object itself (here Person)

private Map<String, Person> people;

I tried something like this but it gives me an error:

PersonCache = people.stream()
      .collect(toMap(Person::getID, Person));

Thanks for your help

1

1 Answer 1

4

I think you want this:

Map<String, Person> result = fetchedPeople.stream().collect(Collectors.toMap(Person::getID, e -> e));

I don't know if there is a way to return "the element itself" without supplying a lambda function that does that, the e -> e part.

Sign up to request clarification or add additional context in comments.

3 Comments

yeah thanks. This worked!
Super elegant solution! So simple and clean! Thank you

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.