Java EE 8: Convenient JsonArray Collector

Java EE 8 with JSON-P 1.1 introduces a java.util.stream.Collector implementation which converts a Collection<JsonObject> into a JsonArray instance:



import java.util.Arrays;
import java.util.List;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.stream.JsonCollectors;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;

public class JSONPTest {

    private List<JsonObject> list;
        
    @Before
    public void init() {
        this.list = Arrays.asList(next(), next());
    }

    public JsonObject next() {
        return Json.createObjectBuilder().
                add("number", System.currentTimeMillis()).
                build();
    }                
    
    @Test
    public void jsonArrayCollector() {
        JsonArray array = this.list.
                stream().
                collect(JsonCollectors.toJsonArray());
        assertThat(array.size(), is(list.size()));
    }
        

In Java EE 7 you would have to either write a custom collector or use a JsonArrayBuilder for the conversion:



        @Test
        public void toJsonArrayConversion() {
            JsonArrayBuilder builder = Json.createArrayBuilder();
            this.list.forEach(builder::add);
            JsonArray array = builder.build();
            assertThat(array.size(), is(list.size()));
        }    
See you at Java EE Workshops at Munich Airport, Terminal 2 and especially at Java EE 8 on Java 9. Is Munich's airport too far? Learn from home: airhacks.io.


NEW online workshop: WebStandards Igniter (online)

Airport MUC workshops: Java EE 8, Java 9: Bootstrap, Effective, Architectures, Single Page Apps, Progressive Web Apps, HTML 5, ES 6, CSS 3 and Microservices

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License