Search code examples
javajsonjacksonjava-stream

How to find a nested element in the JSON with using stream()?


I was working on my project, then I need the reach an element in the JSON data that looks like:

[
  {
    "firstname": "Julide",
    "school": [
      {
        "surname": "Batur",
        "major": 
          {
            "date": 1615370705561,
            "teacher": "Mehmet"
          }
        ]
       }
     ]
   }
]

So I can reach the element of name with:

var myData = data().
                stream().
                filter(x -> x.getFirstname().equals("Julide"))
                .collect(Collectors.toList())
                .get(0);

So, how to reach the teacher with using stream() in java 8?

Also, the getFirstname() where I called:

@Getter
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
        "firstname",
        "school",
})
public class Package {
@JsonProperty("firstname")
    private String firstname;
@JsonProperty("school")
    private List<School> school;
}

Solution

  • Assuming standard getters, the following should work:

    data.stream()
            .filter(x -> x.getSchools().stream()            // for each school...
                    .map(School::getMajor)                  // ... map it to the major...
                    .map(Major::getTeacher)                 // ... map the major to the teacher
                    .anyMatch(Predicate.isEqual("Mehmet"))) // return true, if any teacher is "Mehmet"
            .findFirst()      // return the first student satisfying this criteria...
            .orElse(null));   // ... or null if none match
    

    Ideone demo (the POJOs were simplified to the necessary fields to solve the problem).

    The code will return the first Trainee found that has a School, which has a Course, whose teacher is "Mehmet", or null if no such Trainee is found.