Home > Software engineering >  how to avoid a nested for loop in this problem
how to avoid a nested for loop in this problem

Time:11-05

given these object

Test

 int one;
 int two;
 List<AnotherObject> testList.

AnotherObject

 string name;
 int three; 
 List<AthirdObject> anotherList;

AThirdObject

 string surname;
 int    id;
 

assuming we have List < Test > how can i reach AThirdObject without using a nested for loop , thx in advance

CodePudding user response:

Stream::flatMap should be used here to provide "access" to the lowest level of nested lists assuming the getters are implemented properly in the sample classes:

List<Test> input = ...; // define input data

List<AThirdObject> nestedList = input
    .stream() // Stream<Test>
    .flatMap(t -> t.getTestList().stream()) // Stream<AnotherObject>
    .flatMap(ao -> ao.getAnotherList().stream()) // Stream<AThirdObject>
    .collect(Collectors.toList());
  • Related