[英]How is the implementation of LinkedHashMap different from HashMap?
[英]How to get a limited number of values from a HashMap or LinkedHashMap?
假设我有一个包含216个条目的LinkedHashMap
,我如何从LinkedHashMap<Integer, Object>
获取前100个值(此处为Object
类型)。
首先,按照你的标题对HashMap
执行此操作没有多大意义 - HashMap
没有特定的顺序,并且顺序可能会在调用之间发生变化。 但是对于LinkedHashMap
更有意义。
在那里,我会使用Guava的Iterables.limit
方法:
Iterable<Object> first100Values = Iterables.limit(map.values(), 100);
要么
// Or whatever type you're interested in...
Iterable<Map.Entry<Integer, Object>> firstEntries =
Iterables.limit(map.entrySet(), 100);
然后,您可以从中创建一个列表,或者迭代它,或者您想要做的任何事情。
你可以做:
Map<Integer, Object> records;
List<Entry<Integer, Object>> firstHundredRecords
= new ArrayList<Entry<Integer, Object>>(records.entrySet()).subList(0, 100);
虽然请注意,这将复制地图中的所有条目。
使用库仅复制所需的记录。
Map<Integer, Object> records;
List<Entry<Integer, Object>> firstHundredRecords = new ArrayList<>();
for(Entry<Integer, Object> entry : records.entrySet()) {
firstHundredRecords.add(entry);
if (firstHundredRecords.size()>=100) break;
}
这个丑陋的单线程会做(并在问题的情况下返回一个ArrayList<Object>
):
Collections.list(Collections.enumeration(lhMap.values())).subList(0, 100)
这也适用于HashMap
,但HashMap
由HashSet
支持,并不保证您将获得输入的前100个值; 它适用于其他类型,具有类似的限制。
笔记:
(根据OP的评论)
Map<Integer, Pair<Double, SelectedRoad>> hashmap3 =
new LinkedHashMap<Integer, Pair<Double, SelectedRoad>>();
// [...] add 216 elements to hasmap3 here somehow
ArrayList<Pair<Double,SelectedRoad>> firstPairs =
Collections.list(Collections.enumeration(hashmap3.values())).subList(0, 100)
// you can then view your Pairs' SelectedRow values with them with:
// (assuming that:
// - your Pair class comes from Apache Commons Lang 3.0
// - your SelectedRoad class implements a decent toString() )
for (final Pair<Double, SelectedRoad> p : firstPairs) {
System.out.println("double: " + p.left);
System.out.println("road : " + p.right);
}
你可以使用柜台。 当你的计数器达到100时,你的foreach循环将退出。
编写一个使用Iterator.next()
100次的循环,然后停止。
我想谈谈NavigableMap
和SortedMap
- 但是它们的接口是根据键而不是索引来定义的。 但它们可能会有用,具体取决于您的实际潜在问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.