How to have a key with multiple values in a map?

前端 未结 6 605
轻奢々
轻奢々 2020-12-10 17:10

I have a map like this

Map map=new HashMap();//HashMap key random order.
map.put(\"a\",10);
map.put(\"a\",20);
map.put(\"a\",30);
map.put(\"b\",10);

System.         


        
6条回答
  •  时光说笑
    2020-12-10 17:52

    Have you checked out Guava Multimaps ?

    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.

    If you really want to use standard collections (as suggested below), you'll have to store a collection per key e.g.

    map = new HashMap>();
    

    Note that the first time you enter a new key, you'll have to create the new collection (List, Set etc.) before adding the first value.

提交回复
热议问题