0

enter image description here


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...

hardcode
  • 395
  • 3
  • 19

2 Answers2

2

Store them in a map, with each line of input append that to any existing value.

eg somthing like (sudo code)

Map map= new HashMap(); for (key,value) in inputdata map.put(key, join(map.get(key),value));

Arthur
  • 3,376
  • 11
  • 43
  • 70
0

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);
Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69