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

前端 未结 6 618
轻奢々
轻奢々 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:44

    To implement what you want using the Java standard library, I would use a map like this:

    Map> multiValueMap = new HashMap>();
    

    Then you can add values:

    multiValueMap.put("a", new ArrayList());
    multiValueMap.get("a").add(new Integer(10));
    multiValueMap.get("a").add(new Integer(20));
    multiValueMap.get("a").add(new Integer(30));
    

    If this results uncomfortable for you, consider wrapping this behaviour in a dedicated Class, or using a third-party solution, as others have suggested here (Guava Multimap).

提交回复
热议问题