Shubham Ranka
Shubham Ranka

Reputation: 41

How do I add multiple values to the same key in a TreeMap?

My tree Map is

Map<String, Double> restrMap = new TreeMap<String, Double>(); 

While adding the below two value to the treeMap, it only shows one. The second value, when comes updates the first one.

6, 8.00
6, 5.00

How can I add two values for the same key, perhaps in different rows?

Upvotes: 4

Views: 5642

Answers (3)

BK Batchelor
BK Batchelor

Reputation: 457

Java does not have multimap, but you could uses another container in the map value.

Map<String, List<Double>> restrMap = new TreeMap<String, List<Double>>(); 

Upvotes: 2

Jean Logeart
Jean Logeart

Reputation: 53819

A map has only one value associated to a specific key.

If you want several values, you can:

  • use Guava's Multimap
  • use Apache Commons Collections MultiMap
  • use a Map<Key, Set<Value>> or any other collection for the values that would meet your needs

Upvotes: 2

Marc
Marc

Reputation: 174

If you are adding multiple values to the same key, consider having a Map of Lists.

Map<String, List<Double>> restrMap = new TreeMap<String, List<Double>>();

Upvotes: 5

Related Questions