what java collection that provides multiple values for the same key

后端 未结 3 957
清歌不尽
清歌不尽 2021-01-03 00:58

what type of java collection that returns multiple values for the same key?

example, I want to return 301,302,303 for key 300.

3条回答
  •  自闭症患者
    2021-01-03 01:25

    You can use a List as the value of your Map:

    List list = new ArrayList();
    list.add(301);
    list.add(302);
    list.add(303);
    
    Map> map = new HashMap>();
    map.put(300, list);
    
    map.get(300); // [301,302,303]
    

    Alternatively, you can use Multimap from Guava, as suggested by biziclop, which has a much cleaner syntax, and lots of other very useful utility methods:

    Multimap map = HashMultimap.create();
    map.put(300, 301);
    map.put(300, 302);
    map.put(300, 303);
    
    Collection list = map.get(300); // [301, 302, 303]
    

提交回复
热议问题