简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM