java 如何在HashMap中获取前10个键值对
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9923616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fetch first 10 key value pairs in HashMap
提问by Vijay Selvaraj
I am trying to iterate only the first "n" values in my Map, is there any method available or i need to control it only with a count variable.
我试图只迭代我的 Map 中的前“n”个值,是否有任何可用的方法,或者我只需要使用计数变量来控制它。
Below is an example, i have sorted a group of names belong to the same city. Now i only want the first 10 city and the person names in it.
下面是一个例子,我对属于同一个城市的一组名称进行了排序。现在我只想要前 10 个城市和其中的人名。
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
List<String> list = entry.getValue();
// Display list of people in City
}
Is there a Map implementation that can hold fixed number of key,value pairs? Please get some directions.
是否有可以保存固定数量的键值对的 Map 实现?请得到一些指示。
Thanks,
谢谢,
-Vijay Selvaraj
-维杰·塞尔瓦拉吉
回答by NPE
How to fetch first 10 key value pairs in
HashMap
如何获取前 10 个键值对
HashMap
HashMap
is unordered. This makes the question ill-posed (unless by "first" you mean "arbitrary").
HashMap
是无序的。这使得问题不合适(除非“首先”您的意思是“任意”)。
If you want a consistent ordering of keys, you need to change the type of your map to a SortedMap
, such as TreeMap
.
如果您希望键的顺序一致,则需要将映射的类型更改为 a SortedMap
,例如TreeMap
。
Alternatively, if it's the oldest elements you're after (i.e. the ones you've inserted first), then LinkedHashMap
is the answer.
或者,如果它是您所追求的最旧元素(即您首先插入的元素),那么LinkedHashMap
就是答案。
As to actually getting the first n
elements, a loop with a counter is a pretty reasonable way to do it.
至于实际获取第一个n
元素,带有计数器的循环是一种非常合理的方法。
回答by aioobe
I am trying to iterate only the first "n" values in my Map, is there any method available or i need to control it only with a count variable.
我试图只迭代我的 Map 中的前“n”个值,是否有任何可用的方法,或者我只需要使用计数变量来控制它。
The closest thing you'll find using only the standard Collections API (which still is slightly worse than a counter variable IMO) is the following:
您会发现仅使用标准 Collections API(它仍然比计数器变量 IMO 稍差)最接近的事情如下:
List<Map.Entry<String, List<String>> entryList =
new ArrayList<Map.Entry<String, List<String>>(map.entrySet());
for (Map.Entry<String, List<String>> entry : entryList.subList(0, 10)) {
List<String> list = entry.getValue();
// Display list of people in City
}
The lengthy type parameters could be avoided either by using the fancy diamond from Java 7:
使用 Java 7 中的花式菱形可以避免冗长的类型参数:
List<Map.Entry<String, List<String>> entryList = new ArrayList<>(map.entrySet());
or by using iterating over the keys and .get
the corresponding values.
或者通过使用迭代键和.get
相应的值。
回答by Churk
List<List<string>> list = new ArrayList<List<String>>();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
if (list.size() > 9) break;
list.add(entry.getValue());
}