Perform stream operation on the sub-lists inside a List<List<Integer>>

Advertisements

I have a Student class:

public class Student {
    private String name;
    private String marks;
    private List<Integer> percent;
    
}

There is a List defined as below in another class:

stud1.setMarks("20");
stud1.setName("Sumit");
stud1.setRollNo(1);
stud1.setPercent(Arrays.asList(20,30,40));

stud2.setMarks("50");
stud2.setName("Thakur");
stud2.setRollNo(2);
stud2.setPercent(Arrays.asList(25,35,45));

stud3.setMarks("70");
stud3.setName("Dhawan");
stud3.setRollNo(3);
stud3.setPercent(Arrays.asList(50,60));
List<Student> list = new ArrayList<Student>();
list.add(stud1);
list.add(stud2);
list.add(stud3);

I want to perform operation on this list on percent attribute to get output as List<List> by multiplying it by 10 i.e.

[[200,300,400],[250,350,450],[500,600]]

I tried with below code but flatMap is flattening entire list.

List<Integer> numList   = list.stream().map(Student::getPercent).flatMap(List :: stream).map(j->j*10).collect(Collectors.toList());
[200, 300, 400, 250, 350, 450, 500, 600]

>Solution :

You need to stream and collect the result separately:

List<List<Integer>> collect = list.stream()
    .map(student ->  student.getPercent().stream().map(j -> j *10).collect(Collectors.toList()))
    .collect(Collectors.toList());

Leave a ReplyCancel reply