HashMap with multiple values under the same key

2018-12-31 16:42发布

Is it possible for us to implement a HashMap with one key and two values. Just as HashMap?

Please do help me, also by telling (if there is no way) any other way to implement the storage of three values with one as the key?

标签: java
19条回答
十年一品温如言
2楼-- · 2018-12-31 16:50

Can be done using an identityHashMap, subjected to the condition that the keys comparison will be done by == operator and not equals().

查看更多
姐姐魅力值爆表
3楼-- · 2018-12-31 16:53

Another nice choice is to use MultiValuedMap from Apache Commons. Take a look at the All Known Implementing Classes at the top of the page for specialized implementations.

Example:

HashMap<K, ArrayList<String>> map = new HashMap<K, ArrayList<String>>()

could be replaced with

MultiValuedMap<K, String> map = new MultiValuedHashMap<K, String>();

So,

map.put(key, "A");
map.put(key, "B");
map.put(key, "C");

Collection<String> coll = map.get(key);

would result in collection coll containing "A", "B", and "C".

查看更多
看风景的人
4楼-- · 2018-12-31 16:56

Take a look at Multimap from the guava-libraries and its implementation - HashMultimap

A collection similar to a Map, but which may associate multiple values with a single key. If you call put(K, V) twice, with the same key but different values, the multimap contains mappings from the key to both values.

查看更多
查无此人
5楼-- · 2018-12-31 16:56

You can do it implicitly.

// Create the map. There is no restriction to the size that the array String can have
HashMap<Integer, String[]> map = new HashMap<Integer, String[]>();

//initialize a key chosing the array of String you want for your values
map.put(1, new String[] { "name1", "name2" });

//edit value of a key
map.get(1)[0] = "othername";

This is very simple and effective. If you want values of diferent classes instead, you can do the following:

HashMap<Integer, Object[]> map = new HashMap<Integer, Object[]>();
查看更多
看淡一切
6楼-- · 2018-12-31 16:57

I could not post a reply on Paul's comment so I am creating new comment for Vidhya here:

Wrapper will be a SuperClass for the two classes which we want to store as a value.

and inside wrapper class, we can put the associations as the instance variable objects for the two class objects.

e.g.

class MyWrapper {

 Class1 class1obj = new Class1();
 Class2 class2obj = new Class2();
...
}

and in HashMap we can put in this way,

Map<KeyObject, WrapperObject> 

WrapperObj will have class variables: class1Obj, class2Obj

查看更多
不再属于我。
7楼-- · 2018-12-31 16:59
HashMap<Integer,ArrayList<String>> map = new    HashMap<Integer,ArrayList<String>>();

ArrayList<String> list = new ArrayList<String>();
list.add("abc");
list.add("xyz");
map.put(100,list);
查看更多
登录 后发表回答