How to filter through a JSON Document using Java 8 Stream API

This tutorial will teach you how to filter through a JSON Document using Java 8 Stream API.

Java 8 streams are wrappers around a data source, which allow us to operate with a data source, making bulk processing convenient and fast. A stream does not store data and, for this reason, is not a data structure. It also never modifies the underlying data source.

There are many usages of Java 8 streams API however we will show here how it can be used to filter through data. Consider the following example:

List<String> list = Arrays.asList("apple", "peach", "banana");

List<String> result = list.stream()                // convert list to stream
        .filter(line -> !"apple".equals(line))     // we exclude apple
        .collect(Collectors.toList());              // collect the output and convert streams to a List

result.forEach(System.out::println);                //output : peach banana

How can we use the same to filter a JSON Document? Let’s assume you have the following JSON Document:

{
  "name": "School ABC",
  "topics": [
    "Math",
    "Science",
    "Music",
    "History",
    "English"
  ],
  "classrooms": [
    "SectionA",
    "SectionB",
    "SectionC"
  ],
  "notes": null,
  "active": true,
  "visitors": 10000000
}

So, assumed that you have loaded your javax.json.JsonObject in a variable named ‘jsonObject’, here is how you can filter through the topics which start with ‘M’:

private JsonObject jsonObject = loadJsonObject();

public List<String> filterJsonArrayToList() {
    List<String> topics = jsonObject.getJsonArray("topics").stream()
            .filter(jsonValue -> ((JsonString) jsonValue).getString().startsWith("M"))
            .map(jsonValue -> ((JsonString) jsonValue).getString())
            .collect(Collectors.toList());
    return topics;
}

That will retur a List of Strings (‘Math’,’Music’). On the other hand, if you want it as JsonArray, you can use the following code:

public JsonArray filterJsonArrayToJsonArray() {
    JsonArray topics = jsonObject.getJsonArray("topics").stream()
            .filter(jsonValue -> ((JsonString) jsonValue).getString().startsWith("C"))
            .collect(JsonCollectors.toJsonArray());
    return topics;
}