1

Let's say that I have a LinkedHashMap<Integer,Point2D.Double>, and I put a key and a value to it, like .put(2,new Point2D.Double(34,32));

My problem is that sometimes I need to put a key and a value in it that already exists, and the LinkedHashMap replaces it.

Like, I already have the key 2 and the value Point2D.Double(34,32), and I need to add it another time.

Why is it replacing that key/value by adding the same to the map, and is there a way to solve this issue (maybe via another sort of map)?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Julien
  • 49
  • 5
  • 4
    Possible duplicate of [HashMap: One Key, multiple Values](http://stackoverflow.com/questions/8229473/hashmap-one-key-multiple-values) – khelwood Feb 09 '17 at 10:13
  • 1
    Seems to be a design problem and I fail to read your actual intentions. Do you want to keep both values? Or only the first value? From your questions it seems you do not want to keep the second instead of the first. – pintxo Feb 09 '17 at 10:17

1 Answers1

1

If the order of Point is not important, init your hashmap as:

HashMap<Integer,HashSet<Point2D.Double>> hashmap = new HashMap<Integer,HashSet<Point2D.Double>>();

instead of using

hashmap.put(1,new Point2D.Double(34,32));

use the following code:

if(hashmap.get(key) == null){
  value = new HashSet<Point2D.Double>();
}else{
  value = hashmap.get(key);
}
value.add(point_to_add);
hashmap.put(key,value);

If the order of the inserted Points is important, use an (Array-)List instead of a hashSet

EDIT

AS GPI mentioned: Using JAVA 8 you could also do it this way:

map.computeIfAbsent(key, k -> new HashSet<>()).add(value)
osanger
  • 2,276
  • 3
  • 28
  • 35