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

samjo
  • 47
  • 1
  • 6
  • after reading the suggested answer, it turned out my question is similar to this question https://stackoverflow.com/questions/20363719/java-8-listv-into-mapk-v – samjo Mar 30 '21 at 15:36

1 Answers1

2

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.

CryptoFool
  • 21,719
  • 5
  • 26
  • 44