List of objects to map in java 8

北城以北 提交于 2020-01-21 07:23:35

问题


I have a class like this

ObjectA
id 
type

where id is unique but the type can be duplicate so if I have a list of ObjectA like this

(id, type) = (1, "A") , (2, "B"), (3, "C"), (4, "A")

then I want Map<type, List<id>> where map is

< "A",[1,4],
  "B",[2],
  "C",[3] >

It is working with Java 7 but can't find a way to do it in Java 8. In Java 8 I can create key, value pair but not able to create a list if a type is same.


回答1:


yourTypes.stream()
         .collect(Collectors.groupingBy(
               ObjectA::getType,
               Collectors.mapping(
                    ObjectA::getId, Collectors.toList()
)))



回答2:


A way to do it without streams:

Map<String, List<Integer>> map = new HashMap<>();
list.forEach(object -> 
    map.computeIfAbsent(object.getType(), k -> new ArrayList<>())
        .add(object.getId()));

This uses Iterable.forEach and Map.computeIfAbsent to iterate the list and group its elements (here named object) by its type attribute, creating a new ArrayList if there was no entry for that type in the map yet. Then, the id of the object is added to the list.




回答3:


Though you got some nice answer. I would like to share another way of doing same. It's when you have to tackle really complex conversions to map.

class Student {
    private String name;
    private Integer id;
//getters / setters / constructors
}

            Map<String, List<Integer>> map = Arrays.asList(
            new Student("Jack", 2),
            new Student("Jack", 2),
            new Student("Moira", 4)
    )
            .stream()
            .collect(
                    Collectors.toMap(
                            Student::getName,
                            student -> {
                                List list = new ArrayList<Integer>();
                                list.add(student.getId());
                                return list;
                            },
                            (s, a) -> {
                                s.add(a.get(0));
                                return s;
                            }
                    )
            );

Notice how complex you could play with value and return the new value accordingly.

toMap parameters are respectively keyMapper function, valueMapper function and merger respectively.

Cheers!




回答4:


Employee list to map

List<Employee> list = new ArrayList<>();
            list.add(new Employee(1, "John",80000));
            list.add(new Employee(2, "Jack", 90000));
            list.add(new Employee(3, "Ricky", 120000));


            // key = id, value - name
            Map<Integer, String> result1 = list.stream().collect(
                    Collectors.toMap(Employee::getId, Employee::getName));


来源:https://stackoverflow.com/questions/48747537/list-of-objects-to-map-in-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!