Java LinkedHashSet 向后迭代

2022-01-17 00:00:00 iteration set java linkedhashset

如何遍历 LinkedHashSet 从最后一项到第一项?

解决方案

如果你想继续使用集合,你可以使用如下:

LinkedHashSet;设置 = ...链表<T>list = new LinkedList<>(set);迭代器<T>itr = list.descendingIterator();而(itr.hasNext()){T 项目 = itr.next();//做一点事}

如果您可以改用数组,可以查看 hvgotcodes 的答案.p>

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.

相关文章