1

I want to create map, where many values will be assign to one key.

Let say, that i have many toys in my database.

When i do select from database i have something like this:

name | age to play

car   |  4-6
doll  |  2-4
bike  |  4-6
lego  |  6-8
plain |  6-8

I want to make loop in java and group everything in map, where key will be "age to play".

In my mind it will look like this:

2-4 -> {doll}
4-6 -> (car, bike)
6-8 -> {lego, plain}

I would like to make hashmap:

HashMap map = new HashMap();

for(Toys toy : toys){

map.add(toy.age, toy.name);

}

But it's wrong. How i can do it ?

Ilkar
  • 2,113
  • 9
  • 45
  • 71
  • Probably, you may find your answer at the following link : http://stackoverflow.com/questions/8229473/hashmap-one-key-multiple-values – BST Kaal Jun 02 '14 at 12:46

3 Answers3

3

Use MultivalueMap from Oracle or Multimap from Google Guava.

Petr Janeček
  • 37,768
  • 12
  • 121
  • 145
Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
2

You could use a Map<MyRange, List<String>>. BTW you use put rather than add to set the associated key with its corresponding value

Reimeus
  • 158,255
  • 15
  • 216
  • 276
0
 Map<Object,ArrayList<Object>> multiMap = new HashMap<Object,ArrayList<Object>>();
hari
  • 1,874
  • 1
  • 16
  • 10