adam bien's blog

Converting a Map Into javax.json.JsonObject with Java 8 📎

With a custom Collector:


import java.util.Map;
import java.util.stream.Collector;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;


public interface JsonCollectors {

    public static <T> Collector<Map.Entry<T, T>, ?, JsonObjectBuilder> toJsonBuilder() {
        return Collector.of(Json::createObjectBuilder, (t, u) -> {
            t.add(String.valueOf(String.valueOf(u.getKey())), String.valueOf(u.getValue()));
        }, JsonCollectors::merge);
    }

    static JsonObjectBuilder merge(JsonObjectBuilder left, JsonObjectBuilder right) {
        JsonObjectBuilder retVal = Json.createObjectBuilder();
        JsonObject leftObject = left.build();
        JsonObject rightObject = right.build();
        leftObject.keySet().stream().forEach((key) -> retVal.add(key, leftObject.get(key)));
        rightObject.keySet().stream().forEach((key) -> retVal.add(key, rightObject.get(key)));
        return retVal;
    }
}


...a Map<String, String> can be easily converted into a JsonObject:

    public JsonObject environmentVariables() {
        Map<String, String> environment = System.getenv();
        return environment.entrySet().
        stream().
        collect(JsonCollectors.toJsonBuilder()).
		build();
    }

The sample above is taken from github.com/AdamBien/ping

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.