How can I iterate through items of a LinkedHashSet
from the last item to the first one?
If you want to continue to use collections, you could use the following:
LinkedHashSet<T> set = ...
LinkedList<T> list = new LinkedList<>(set);
Iterator<T> itr = list.descendingIterator();
while(itr.hasNext()) {
T item = itr.next();
// do something
}
If you're fine with using an array instead, you could take a look at hvgotcodes' answer.
new LinkedList<>(set)
will copy all items, won't it? –
Plank I would use toArray and just use a reverse for loop.
There might be a better way to do it, but that should work. toArray
guarantees any order is preserved
If this set makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.
Something like
Set<MyType> mySet = new LinkedHashSet();
...
MyType[] asArray = mySet.toArray(new MyType[0]);
for (int i = asArray.length - 1; i>=0; i--){
..
}
MyType[] asArray = mySet.toArray();
–
Peeling This is another way:
LinkedHashSet<T> set = ...
List<T> list = new ArrayList<>(set);
Collections.reverse(list);
for( T item : list ){
...
}
You could put the elements into an ArrayList
and then use the ArrayList
's ListIterator
.
ListIterator<T> l = new ArrayList<T>(yourLinkedHashList).listIterator();
// ListIterator can iterate in reverse
while(l.hasPrevious()) {
T obj = l.previous();
}
As of Java 21, the reversed()
method on LinkedHashSet
can be used. This reversed view of the set can be used to iterate in reverse order.
for (Object o : myLinkedHashSet.reversed()) {
System.out.println(o);
}
Now from java 21 onwards you can use reversed()
method of SequancedSet
to reverse a collection element.
LinkedHashSet lhs=....
....
.....
SequencedSet sequencedSet=lhs.reversed();
© 2022 - 2025 — McMap. All rights reserved.