Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[[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());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading