Java – How do I merge a temporary map onto a permanent map so that I can log multiple items of the same key?

How do I merge a temporary map onto a permanent map so that I can log multiple items of the same key?… here is a solution to the problem.

How do I merge a temporary map onto a permanent map so that I can log multiple items of the same key?

So I have two mappings where the key is based on the length of the word. Whenever there is a word of the same length, I want it added to that key.

I

want to do this by using the map.merge() function, however, I’m not sure how to do it after looking at the docs. I tried looking at other resources, but it didn’t help much.

Map<Integer, String> map = new HashMap<Integer, String>();

Map<Integer, String> map = new HashMap<Integer, String>();

String[] wordsSplit = doc.split(" ");
for(int i = 0; i < wordsSplit.length; i++) {
    int key = wordsSplit[i].length();
    Map<Integer, String> tempMap = new HashMap<Integer, String>();
    tempMap.put(key, wordsSplit[i]);
    merge here
    map.merge(key, map.keySet(), map.get(key) + ", " + wordsSplit[i]);  
}

EDIT: This question is different because here I’m trying to figure out how to map in the context of merging a temporary map into an old map.

This means, for example, that if multiple items share the same key, the result will be more like: key: “Car, bar, Tar"

Solution

First you need a merge function to concatenate words of the same length, separated by “, ";

BiFunction<String, String, String> mergeFunction = (i, j) -> {      
    return i + ", " + j;
};

then map.merge(key, x, mergeFunction); Combines the elements of a wordsSplit array based on length. Below the key is the length of the word, and x stands for wordsSplit[i].

Stream.of(wordsSplit).forEach(x -> {
    int key = x.length();
    map.merge(key, x, mergeFunction);
});

Or you can directly merge the body of the function (i, j) -> { return i + ", "+ j; } to map.merge() instead of defining mergeFunction:

Stream.of(wordsSplit).forEach(x -> {
    int key = x.length();
    map.merge(key, x, (i, j) -> { return i + ", " + j; });
});

Related Problems and Solutions