要在java 8中映射的对象列表

时间:2018-02-12 13:23:21

标签: java-8 java-stream

我有一个这样的课程

ObjectA
id 
type

其中id是唯一的,但类型可以重复,所以如果我有像这样的ObjectA列表

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

然后我想Map<type, List<id>>在哪里 地图是

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

它正在使用Java 7,但无法在Java 8中找到方法。在Java 8中,我可以创建键值对,但如果类型相同则无法创建列表。

5 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:3)

没有溪流的方法:

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

这会使用Iterable.forEachMap.computeIfAbsent来迭代list并按其object属性对其元素(此处命名为type)进行分组,从而创建一个新{ {1}}如果地图中没有该类型的条目。然后,将对象的ArrayList添加到列表中。

答案 2 :(得分:1)

虽然你有一个很好的答案。我想分享另一种做同样的方式。当你必须处理真正复杂的转换以进行映射时。

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

请注意您可以使用值进行复杂化并相应地返回新值。

toMap参数分别是keyMapper函数,valueMapper函数和merger。

干杯!

答案 3 :(得分:0)

员工列表映射

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

答案 4 :(得分:0)

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> result = list.stream().collect(
Collectors.toMap(Employee::getId, Employee::getName));

If you want to give a constant value instead of name:
// key = id, value - "ABC"
Map<Integer, String> result = list.stream().collect(
Collectors.toMap(Employee::getId, emp-> "ABC"));
相关问题