HashMap with multiple Value [duplicate]

梦想与她 提交于 2019-11-30 19:50:35

问题


I want to implement Hash table with multiple values in java i.e

// if sample is a hashmap
sample.put(1,1);
sample.put(1,2);

and sample.get(1); will return 2 values.

How can i achieve this?


回答1:


You can use a Multimap instead. It keeps multiple values for a key in a list. There are implementations in commons-collections and in Guava.

Multimap<String, String> multimap = ArrayListMultimap.create();   
multimap.put("ducks", "Huey");
multimap.put("ducks", "Dewey");
multimap.put("ducks", "Louie");
Collection<String> ducks = multimap.get("ducks");
System.out.println(ducks); // [Huey, Dewey, Louie]

It is similar to using a Hashmap where the values are lists, but you don't have to explicitly create the lists.

The same example done the do-it-yourself way looks like:

Map<String, List<String>> map = new HashMap<>();
map.put("ducks", new ArrayList<String>());
map.get("ducks").add("Huey");
map.get("ducks").add("Dewey");
map.get("ducks").add("Louie");
// or as an alternative to the prev 4 lines:
// map.put("ducks", new ArrayList<String>(
//     new String[] {"Huey", "Dewey", "Louie"}));
Collection<String> ducks = map.get("ducks");
System.out.println(ducks); // [Huey, Dewey, Louie]

Note that you can use the Multimap as a builder and call asMap on it to return a map.




回答2:


Try HashMap<Key, List<Value>> You will need to manage the list, creating if it doesn't exist already, and adding to it if you need.

Guava also provides a Multimap implementation




回答3:


Do it this way

Map<String, List> map = new HashMap<String, List>();
List listOne = new ArrayList();
for(int i=0;i<4;i++){
    listOne.add(i);
}
List listTwo = new ArrayList();
for(int i=4;i<6;i++){
    listTwo.add(i);
}
map.put("listOne",listOne);
map.put("listTwo",listTwo);

Or you can even use Guava's Multimap



来源:https://stackoverflow.com/questions/25917531/hashmap-with-multiple-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!