JavaEE 7 brings an API for JSON arrays (the surprising JsonArray ;)), Java 8 brings a stream API and lambdas so now you can combine both to create a JsonArray from a Collection!
Side note: the snippet of this article have been tested with Apache Fleece as JSon Processing implementation.
The idea is to start from a collection, transform it with Java 8 stream API (in the example I took only the public id field of an object) and convert the produced stream to a JsonArray. For this last part we can simply use collect() method of Java 8 stream API and JsonBuilderFactory to create a new JsonArrayBuilder for the convertion:
@ApplicationScoped public class ResourceService { @Inject // just for the sample private SomeCollectionProvider collections; @Inject // created from Json.createBuilderFactory(Collections.emptyMap()) private JsonBuilderFactory builderFactory; public JsonArray collectionToJsonArray() { return collections.createACollection() .stream() .map(myObject -> myObject.id) // field is public .collect( builderFactory::createArrayBuilder, (a, s) -> a.add(s), (b1, b2) -> b1.add(b2)) .build(); } }
And that’s it! You got a JsonArray of your id from a collection without any loop or complicated code 🙂
Want more content ? Keep up-to-date on my new blog
Or stay in touch on twitter @rmannibucau
Simpler:
.collect(JsonArray::new, JsonArray::add, JsonArray::addAll));
then you don’t use JavaEE 7 since JsonArray is an interface no?
thanks a lot 🙂