Manu Zi
Manu Zi

Reputation: 2370

Default return value for Collectors.toMap

If we image, we have a object called person and person looks like the follwing:

class Person {
    int id;
    String name;
    String country
    // ...
    // getter/setter
}

And we have a List of Person objects and we want to "convert" it to a map. We can use the following:

Map<Long, List<Person>> collect = personList.stream().
    collect(Collectors.toMap(Person::getId, p -> p));

But it is possible to return a default value for the valuemapper and change the type of the valuemapper?

I thought on something like that:

Map<Long, List<Person>> collect = 
     personList.stream().collect(Collectors.groupingBy(Person::getId, 0));

but with this i get the following error is not applicable for the arguments

I have a workaround but i think it's not really pretty.

Map<Long, Object> collect2 = personList.stream().
    collect(Collectors.toMap(Person::getId, pe -> {
            return 0;
    }));

Upvotes: 3

Views: 2726

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198471

If you want to map every ID of each person to the same value, that's exactly what you need to do, although you can simplify it by writing Collectors.toMap(Person::getId, pe -> 0).

Upvotes: 6

Related Questions