Marinescu Raluca
Marinescu Raluca

Reputation: 277

Java 8 iterate through list and store in Map

List<String> list =new ArrayList<>();
list.add("abcd");
list.add("afsd");
list.add("addd");

Map<String, List<Person>> ordersByInstrumentId = findService.findAllUsers(**list.get(0)**)
                        .stream()
                        .collect(Collectors.groupingBy(Dummy::getId, Collectors.toList()))

My method findAllUsers takes a String as parameter. I want to replace list.get(0) with iteration, so it will call function for each element and store in Map. I tried list.foreach but it returns void so no use

Upvotes: 3

Views: 3288

Answers (1)

Eugene
Eugene

Reputation: 120858

Seems like you would need:

list.stream()
    .flatMap(x -> findService.findAllUsers(x).stream())
    .collect(Collectors.groupingBy(Dummy::getId, Collectors.toList()));

Upvotes: 6

Related Questions