简体   繁体   中英

Create HashMap from List<String>

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?

You can transform the individual Map s 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM