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

With a custom Collector:

import java.util.Map;
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 =;
        JsonObject rightObject =;
        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().

The sample above is taken from

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:

NEW online workshop: WebStandards Igniter (online)

Airport MUC workshops: Java EE 7: Bootstrap, Effective, Architectures, Web, React and Angular, Testing and Microservices

Podcast: and newsletter:

A book about rethinking Java EE Patterns


In case of a rest service to get JSON one can simply use:

public Map<String, String> environmentVariables() {
Map<String, String> environment = System.getenv();
return environment;

Posted by Michael on June 12, 2016 at 09:07 AM CEST #

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