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 ?

1

3 Answers 3

3

Use MultivalueMap from Oracle or Multimap from Google Guava.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0
 Map<Object,ArrayList<Object>> multiMap = new HashMap<Object,ArrayList<Object>>();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.