Reputation: 73
consider as,
HashMap<Integer, String> map = new HashMap<Integer, String>();
i want store like,
map.put(1, "Val-1");
map.put(2, "Val-2");
map.put(1, "Val-3");
map.put(1, "Val-4");
map.put(3, "Val-5");
.
.
. it goes like this
when I give a it should give all the values associated with a key. How can I solve it. Not one HashMap if you know other possibilities please to tell me
Upvotes: 2
Views: 3167
Reputation: 51711
In Java, Map
s do not allow duplicate keys. So, to associate multiple values you'll need to assign every key a List
instead. Also, notice how I'm using an interface type on the reference side.
Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
Now you just have to create your own put()
version that adds to these List
s instead.
public void add(Integer key, String val) {
List<String> list = map.get(key);
if (list == null) {
list = new ArrayList<String>();
map.put(key, list);
}
list.add(val);
}
Here's how you would add and display multiple values
add(1, "one");
add(2, "two");
add(2, "three");
for(Map.Entry<Integer, List<String>> entry: map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
Output :
1 = [one]
2 = [two, three]
Upvotes: 1
Reputation: 393831
You can use a HashMap<Integer,List<String>>
.
You group all the values sharing the same key in a list.
HashMap<Integer,List<String>> map = new HashMap<>();
List<String> l = new ArrayList<>();
l.add("Val-1");
l.add("Val-3");
l.add("Val-4");
map.put(1, l);
l = new ArrayList<>();
l.add("Val-2");
map.put(2, l);
l = new ArrayList<>();
l.add("Val-5");
map.put(3, l);
Upvotes: 6