I have two hashmaps "map0 and map1
", both of them holds keys of type Point
and values of type Double
as shown below.
I am sure that the key will never be duplicate but the values could be and I want to add both of "map0 and map1
" into one Hashmap
so that
I do not lose the duplicate values "I want to keep the duplicate values". After i checked some questions in this website, I used .putAll()
method as shown below in the code, but the problem is, when I combined both maps "map0, map1" into one combined map, I lost the duplicate values as shown below in the results as map0 has value of 20 and map1 has value of 20 as well!
Please let me know how to combine both maps into one without losing the duplicate values
Code:
public static void main(String[] args) {
HashMap<Point, Double> map0 = new HashMap<Point, Double>();
HashMap<Point, Double> map1 = new HashMap<Point, Double>();
map0.put(new Point(32,59), (double) 56);
map0.put(new Point(398,3), (double) 20);
map0.put(new Point(3,3), (double) 209);
map1.put(new Point(32,596), (double) 561);
map1.put(new Point(396,311), (double) 20);
map1.put(new Point(35,34), (double) 2099);
System.out.println("map0.size:"+map0.size());
System.out.println("map1.size:"+map1.size());
HashMap<Point, Double> combine = new HashMap<Point, Double>();
combine.putAll(map0);
combine.putAll(map1);
ValueComparator vc = new ValueComparator(combine);
TreeMap<Point, Double> tree= new TreeMap<Point, Double>(vc);
tree.putAll(combine);
System.out.println("tree.size:"+tree.size());
System.out.println("tree_sorted:"+tree);
}
static class ValueComparator implements Comparator<Point> {
private HashMap<Point, Double> map = null;
public ValueComparator(HashMap<Point, Double> map) {
// TODO Auto-generated constructor stub
this.map = map;
}
public int compare(Point arg0, Point arg1) {
// TODO Auto-generated method stub
return Double.compare(this.map.get(arg0), this.map.get(arg1));
/*
if (this.map.get(arg0) >= this.map.get(arg1)) {
return 1;
} else {
return -1;
}
*/
}
}
output:
map0.size:3
map1.size:3
tree.size:5
tree_sorted:{{398.0, 3.0}=20.0, {32.0, 59.0}=56.0, {3.0, 3.0}=209.0, {32.0, 596.0}=561.0, {35.0, 34.0}=2099.0}
Map<Point, List<Double>>
, won't you?20
. Do you want those keys with the same value be grouped in some way?