List of objects to map in java 8
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));
yourTypes.stream()
.collect(Collectors.groupingBy(
ObjectA::getType,
Collectors.mapping(
ObjectA::getId, Collectors.toList()
)))
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!