Actually I have to merge duplicate key's value into existing key instead of replace, for that which map I have to use, I tried hashmap but it is replacing the values. Thanks...
2 Answers
Java8 Maps have a merge method that let's you modify the value associated to a given key if needed.
Suppose each value is a list (afterall if you want multiple values for a given key)...
List<Integer> l1 = new ArrayList<Integer>(); l1.add(1);
List<Integer> l2 = new ArrayList<Integer>(); l2.add(2);
List<Integer> l3 = new ArrayList<Integer>(); l3.add(3);
List<Integer> l4 = new ArrayList<Integer>(); l4.add(4);
BiFunction<Collection<Integer>,Collection<Integer>,Collection<Integer>> mergeFunc = (old,new)-> { old.addAll(new); return old; };
myMap.merge("one",l1,mergeFunc);
myMap.merge("two",l2,mergeFunc);
myMap.merge("three",l3,mergeFunc});
myMap.merge("one",l4,mergeFunc);
