AntonBoarf
AntonBoarf

Reputation: 1313

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

Upvotes: 3

Views: 115

Answers (2)

Hadi
Hadi

Reputation: 17289

And also you can use toMap with merge function

Map<String,List<String>> map= persons
      .stream()
      .collect(Collectors.toMap(Person::getPersonId,
                        value->new ArrayList<>(Arrays.asList(Person::getRegistrationId)),
                        (l1,l2)->{l1.addAll(l2);return l1;}));

as @Holger commented not to need create a temporary array.

Map<String,List<String>> map= persons
  .stream()
  .collect(Collectors.toMap(Person::getPersonId,
                    value->new ArrayList<>(Collections.singletonList(Person::getRegistrationId)),
                    (l1,l2)->{l1.addAll(l2);return l1;})); 

Upvotes: 0

Eran
Eran

Reputation: 393781

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())));

Upvotes: 7

Related Questions