[英]iterating through a linkedhashmap but over a certain range
So i know how to iterate through a whole linkedhashmap from the beginning, but what if I want to only link through a certain portion from it? 所以我从一开始就知道如何遍历整个linkedhashmap,但是如果我只想从中遍历某个部分怎么办? IE: i want to start from the end and go only 4 elements back. IE:我想从头开始,只返回4个元素。 How would I do that and is it possible? 我该怎么办?有可能吗?
What you are searching for is a ListIterator which would allow you to iterate backwards in a list. 您要搜索的是ListIterator ,它将允许您在列表中向后迭代。 Unfortunately, LinkedHashMap
does not hold a reference towards the previous element, and thus does not provide this iterator. 不幸的是, LinkedHashMap
不保存对先前元素的引用,因此不提供此迭代器。
So, you end up with two solutions. 因此,您最终得到了两种解决方案。 One, you implement the method to find the X last elements: you hold, let's say an array (a circular buffer) of size X and keep there the last X elements you have seen. 一种,实现该方法以找到X个最后一个元素:您持有一个大小为X的数组(循环缓冲区),并在此保留您看到的最后一个X个元素。 This solution is rather inefficient if you call this method frequently and for X much smaller than the size of your map. 如果您频繁调用此方法,并且X的大小比地图的大小小得多,则此解决方案的效率很低。
A second solution is to keep a HashMap
instead of a LinkedHashMap
and an extra List
to maintain the insertion order. 第二种解决方案是保留HashMap
而不是LinkedHashMap
和额外的List
来维护插入顺序。 Eg an ArrayList
or a LinkedList
which provide a ListIterator
and thus, backwards iteration. 例如,提供ListIterator
并因此向后迭代的ArrayList
或LinkedList
。
You have to extend standard implementation and override methods that return appropriate iterator to your own. 您必须扩展标准实现并重写将适当的迭代器返回给您自己的方法。
Iterator<K> newKeyIterator() { return new KeyIterator(); }
Iterator<V> newValueIterator() { return new ValueIterator(); }
Iterator<Map.Entry<K,V>> newEntryIterator() { return new EntryIterator(); }
LinkedHashMap.Entry
is a doubly linked list, so you can go forward and backward as well. LinkedHashMap.Entry
是一个双向链接列表,因此您也可以前进和后退。 LinkedHashMap.LinkedHashIterator
is a base iterator for LinkedHashMap. LinkedHashMap.LinkedHashIterator
是LinkedHashMap.LinkedHashIterator
的基本迭代器。 Make what you need based on it. 根据它做出您需要的东西。
You could use the ListIterator
for this, by doing something like this. 您可以通过执行类似的操作来使用ListIterator
。
List list = new ArrayList<>(map.keySet());
ListIterator li = list.listIterator(list.size());
while (li.hasPrevious()) {
System.out.println(map.get(li.previous()));
}
Since the LinkedHashMap
maintains the order, you could simply create a list from the keys which are going to be in order as well. 由于LinkedHashMap
保持顺序,因此您可以简单地从也将按顺序排列的键中创建一个列表。 Get a ListIterator
from the last index, so that you can traverse backwards having a counter(which I've not shown) to iterator till the no. 从最后一个索引获取ListIterator
,以便您可以向后遍历具有计数器(我没有显示)的迭代器,直到没有为止。 of elements required. 所需的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.