Json API (JavaEE 7) + Java 8: collection to JsonArray

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:

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()
                .map(myObject -> myObject.id) // field is public
                        (a, s) -> a.add(s),
                        (b1, b2) -> b1.add(b2))

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

3 thoughts on “Json API (JavaEE 7) + Java 8: collection to JsonArray

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s