I want to convert a list of Student objects to Map<Long, List<>>
using streams
.
List<Student> list = new ArrayList<Student>();
list.add(new Student("1", "test 1"));
list.add(new Student("3", "test 1"));
list.add(new Student("3", "test 3"));
I want the final outcome in the following way:
Map
Key: 1
Value List: Student("1", "test 1")
Key: 3
Value List: Student("3", "test 1"), Student("3", "test 3")
I tried the following code, but it is reinitializing the Student
objects. Can anyone help me fix the below code?
Map<Long, List<Student>> map = list.stream()
.collect(Collectors.groupingBy(
Student::getId,
Collectors.mapping(Student::new, Collectors.toList())
));