什么java集合为同一个键提供多个值 [英] what java collection that provides multiple values for the same key
本文介绍了什么java集合为同一个键提供多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么类型的java集合会为同一个键返回多个值?
what type of java collection that returns multiple values for the same key?
例如,我要为键300返回301,302,303。
example, I want to return 301,302,303 for key 300.
推荐答案
您可以使用列表
作为 code>:
You can use a List
as the value of your Map
:
List<Integer> list = new ArrayList<Integer>();
list.add(301);
list.add(302);
list.add(303);
Map<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
map.put(300, list);
map.get(300); // [301,302,303]
或者,您可以使用 Multimap
通过biziclop,它有一个更干净的语法,以及许多其他非常有用的实用程序方法:
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<Integer, Integer> map = HashMultimap.create();
map.put(300, 301);
map.put(300, 302);
map.put(300, 303);
Collection<Integer> list = map.get(300); // [301, 302, 303]
这篇关于什么java集合为同一个键提供多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文