Considering Person
class has three fields name(String), age(int), salary(double).
I want to create a map with name as key and value as salary (instead of Person
object itself), if key is not unique then use linkedList to hold the values of all duplicate keys.
I am referring to the solution given in the link given below: Idiomatically creating a multi-value Map from a Stream in Java 8 but still unclear how to create hashmap with Salary as value.
I can create map<String, List<Double>>
with forEach(). code is given below:
List<Person> persons= new ArrayList<>();
persons.add(p1);
persons.add(p2);
persons.add(p3);
persons.add(p4);
Map<String, List<Double>> personsByName = new HashMap<>();
persons.forEach(person ->
personsByName.computeIfAbsent(person.getName(), key -> new LinkedList<>())
.add(person.getSalary())
);
but I am trying to use "groupingBy & collect" to create a map.
If we want Person
object itself as value then the code is given below:
Map<String, List<Person>> personsByNameGroupingBy = persons.stream()
.collect(Collectors.groupingBy(Person::getName, Collectors.toList()));
But I want to create a map with salary as value like given below:
Map<String, List<Double>>
How to achieve this scenario?
You can use Collectors.mapping
to map the Person
instances to the corresponding salaries:
Map<String, List<Double>> salariesByNameGroupingBy =
persons.stream()
.collect(Collectors.groupingBy(Person::getName,
Collectors.mapping(Person::getSalary,
Collectors.toList())));