JsonArray loop using Streams

Viewed 5711

I'm trying to loop a JsonArray using Streams in java, I have looped a JsonObject Using the following code

jsonObject.entrySet().stream()

but there isn't no entrySet() class for JsonArray, How ever I tried using the iterator method but it only printed out one of the JsonObject inside of the JsonArray here is my attempt

.map(JsonArray::iterator)
.map(Iterator::next)
.forEach(System.out::println);

Edit: I'm getting the JsonArray from a JsonObject stream

.map(JsonArray.class::cast)
//need to handle jsonArray
3 Answers

Use StreamSupport.stream(jsonArray.spliterator(), false) to get a Stream of json array.

So your code will look like:-

StreamSupport.stream(jsonArray.spliterator(), false)
             .forEach(....);

These are the utility functions which converts iterator into stream. use these functions to covert your iterator into streams.

public static <T> Stream<T> asStream(Iterator<T> sourceIterator) {
    return asStream(sourceIterator, false);
  }

  public static <T> Stream<T> asStream(Iterator<T> sourceIterator, boolean parallel) {
    Iterable<T> iterable = () -> sourceIterator;
    return StreamSupport.stream(iterable.spliterator(), parallel);
  }

like :

asStream(jsonObject.keys())
   .map(JsonObject::getJSONObject)
   .foreach(//do what you want);

OR

asStream(jsonObject.keys()).forEach();
jsonObject.entrySet().stream()
                .map(entery -> {
                    return StreamSupport.stream(((JsonArray) entery.getValue()).spliterator(), false);
                })
                .forEach(stream->stream.forEach(System.out::println));

Using stream support you can map/convert your jsonArray to stream and then in forEach you get the stream for each jsonArray then you can stream them in that forEach

Related