4

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?

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
Shubham Ranka
  • 41
  • 1
  • 2
  • A map is not a table. Its purpose is to find a value by a key. So there is only one value for a key. You can make that value a container of several objects. – RealSkeptic Mar 26 '15 at 20:20

3 Answers3

5

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>>();
Marc
  • 174
  • 4
2

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
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
2

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>>(); 
BK Batchelor
  • 457
  • 2
  • 6