I have a few simple JSON files that have syntax

"key1": "value1"
"key2": "value2"


I need to create a Map from each of them, and then merge them into one. The following code works as is supposed to:

private TranslationBundle assembleBundle(List<String> translations) {
        TranslationBundle translationBundle = new TranslationBundle();
        Map<String, String> bundledTranslationMap = new HashMap<>();

        translations.forEach(translation -> {
        return translationBundle;

    private Map<String, String> getSingleTranslationMap(String translation){
        ObjectMapper mapper = new ObjectMapper();
            return mapper.readValue(translation, new TypeReference<Map<String, String>>(){});
        }catch (Exception e) {
        return null;

What I want to achieve is to rewrite the code in the assembleBundle method into a more functional one, like

     .collect(collect to single HashMap);

In the collect() method, as far as I know, I have to somehow access the key and value for each result of getSingleTranslationMap. Since there is no variable name assigned to the result of this method, how should it be done? Maybe I'm trying a wrong approach at all?

1 Answers

Eran On Best Solutions

You can transform the individual Maps returned by getSingleTranslationMap into a Stream of map entries, and collect them into a single Map:

Map<String, String> bundledTranslationMap =
                .flatMap(translation -> getSingleTranslationMap(translation).entrySet()

Of course, if getSingleTranslationMap returns a Map with a single Entry, it might make more sense for that method to return a Map.Entry instead of a Map, which would simplify the above Stream pipeline.

P.S., if duplicate keys are possible, you should add a merge function to the toMap() call.