Al Grant
Al Grant

Reputation: 2354

Looping over nested object

I am working with Jackson to parse json data into a series of nested objects in Java.

I then need to loop over some of the nested objects and want to know if you can access a list of nested objects for looping directly.

Currently I can only access the nested objects/nested lists by nesting for loops.

RootNode has a List<VisibleEntities> which in turn has a Dto. Dto has a List<Segments> which has a attribute String transfer .

Looks a bit like this:

enter image description here

Currently I access this by:

        for (VisibleEntities v: rootNode.visibleEntities) {
            for (Segments s: v.dto.segments) {
                if (s.transfer != null) {
                    System.out.println(s.transfer.getName());
                }
            }
       }

Is there a way to loop over rootNode.visibleEntities.dto.segments and print dto.segments.transfer (if not null) directly?

Upvotes: 0

Views: 1110

Answers (1)

Tim Hunter
Tim Hunter

Reputation: 826

If your data is structured as a nested loop then you're going to need to iterate through both loops. You can apply some Java8 streaming if you want to shorten it though.

import java.util.ArrayList;

public class NestedStreamTest {

  public static void main(String[] args) {
    //Following is for example data
    var nest = new ArrayList<ArrayList<Integer>>();
    for(int i = 0; i < 10; i++) {
      var list = new ArrayList<Integer>();
      nest.add(list);
      for(int j = 0; j < 10; j++)
        if(j % 2 == 0)
          list.add(j);
        else
          list.add(null);
    }
    
    //Actual looping starts here
    nest.stream() //Loop through the nest
      .flatMap(list -> list.stream()) //Loop through each list in the nest
      .filter(value -> value != null) //Only allow values which are not null to continue
      .forEach(value -> System.out.println(value.toString())); //Print each filtered value
  }
}

Upvotes: 1

Related Questions