Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert List<Person> to Map<String, List<Double>> instead of Map<String, List<Person>>?

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?

like image 396
Nipun Avatar asked Jan 02 '23 09:01

Nipun


2 Answers

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())));
like image 57
Eran Avatar answered Jan 31 '23 01:01

Eran


Create a Map and then do a forEach, for each item, check your Map if it has a specific key or not, if not, put new key and emptyList to collect your data. Check the code below.

Map<String, List<Double>> data = new HashMap<>();

persons.forEach(
    p->{
       String key = p.getName();
       if(!data.contains(key)){
           data.put(key, new ArrayList());
       }
       data.get(key).add(p.getSalary);
    }
);
like image 36
Febrinanda Endriz Pratama Avatar answered Jan 31 '23 00:01

Febrinanda Endriz Pratama