How Do I Merge A Temporary Map Onto A Permanent Map So That I Can Record Several Items Of The Same Key?

Gorgochef :

So I have two maps where the key is based off of the length of the word. Whenever there is a word with the same amount of length, I want it added to that key.

I want to do this by using the map.merge() function, however, after looking at the documentation I am unsure how to do so. I tried looking at other resources, but not many have helped.

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 am trying to figure out how to map in the context of merging the temporary map onto the the old map.

For instance, this means if there are several items that share the same key, then it would more turn out as: key: "Car, bar, Tar"

Hülya :

First you need a merge function to concat words with same length, seperated with ", ";

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

Then map.merge(key, x, mergeFunction); merges the elements of wordsSplit array according to their length. Below key is length of word, x stands for wordsSplit[i]

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

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

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=97552&siteId=1