-2

Here's an example:

Map<String, Student> getStudentsById(Collection<String> ids) {

  return ids.stream()
       .collect(Collectors.toMap(<id-here>, id -> new Student(id))

}

I'm not sure how to use Collectors.toMap, so that key is the stream element (here in case the ID), and value is some object constructed from the key.

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
Gayan Weerakutti
  • 11,904
  • 2
  • 71
  • 68
  • Does this answer your question? [Convert a Collection to Map> using java 8 streams](https://stackoverflow.com/questions/38947983/convert-a-collection-to-mapstring-collectionstring-using-java-8-streams) – Seba López Aug 25 '20 at 06:40
  • @SebastiánLópez No it's not. This question is about using the same input argument as the key mapper. – Gayan Weerakutti Aug 25 '20 at 06:49

1 Answers1

1

You are passing a String and a Student to Collectors.toMap(), when you should be passing a Function<? super String,? extends String> and a Function<? super String,? extends Student>.

It should be:

Map<String, Student> idToStudent = ids.stream()
     .collect(Collectors.toMap(Function.identity(), id -> new Student(id)));
Andreas
  • 154,647
  • 11
  • 152
  • 247
Eran
  • 387,369
  • 54
  • 702
  • 768