I have a few simple JSON files that have syntax

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

etc.

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 -> {
                bundledTranslationMap.putAll(getSingleTranslationMap(translation).);
        });
        translationBundle.setTranslationMap(bundledTranslationMap);
        return translationBundle;
    }

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

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

translations.stream().
     map(this::getSingleTranslationMap)
     .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

4
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 =
    translations.stream()
                .flatMap(translation -> getSingleTranslationMap(translation).entrySet()
                                                                            .stream())
                .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));

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.