adam bien's blog

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.