Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 : stream and map transformations

I want to turn a List into something different.

I have a POJO class like this (I removed here getters/setters) :

public class Person {
   private String personId;
   private String registrationId;
}

A Person (personId) can have many registrationId, so different Person instances may refer the same real person (but have different registrationId).

I have a List<Person> persons as follows with 3 elements :

persons = [{"person1", "regis1"}, {"person1", "regis2"}, {"person2", "regis1"}];

I would like something like this (so that each key refers to a person and for each person I got the list of registrationId) :

Map<String, List<String>> personsMap = [ "person1" : {"regis1", "regis2"}, "person2" : {"regis2"}]

I know I can do something like this :

Map<String, List<Person>> map = persons.stream().collect(Collectors.groupingBy(Person::getPersonId));

But I got a Map<String,List<Person>> and I would like a Map<String,List<String>>

Any ideas ?

Thanks

like image 415
AntonBoarf Avatar asked Jan 19 '26 03:01

AntonBoarf


1 Answers

Use Collectors.mapping to map the Person instances to the corresponding registrationId Strings:

Map<String, List<String>> map = 
    persons.stream()
           .collect(Collectors.groupingBy(Person::getPersonId,
                                          Collectors.mapping(Person::getRegistrationId,
                                                             Collectors.toList())));
like image 177
Eran Avatar answered Jan 20 '26 19:01

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!