Julien
Julien

Reputation: 49

How to prevent LinkedHashMap from replacing Key/Value?

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)?

Upvotes: 1

Views: 551

Answers (1)

osanger
osanger

Reputation: 2352

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)

Upvotes: 1

Related Questions