可以以相反的顺序为java中的每个循环做一个吗? [英] Can one do a for each loop in java in reverse order?

查看:25
本文介绍了可以以相反的顺序为java中的每个循环做一个吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 Java 以相反的顺序运行 List.

I need to run through a List in reverse order using Java.

那么它在哪里转发:

for(String string: stringList){
//...do something
}

是否有某种方法可以使用 for each 语法以相反的顺序迭代 stringList?

Is there some way to iterate the stringList in reverse order using the for each syntax?

为了清楚起见:我知道如何以相反的顺序迭代列表,但想知道(出于好奇)如何在 for each 样式中执行此操作.

For clarity: I know how to iterate a list in reverse order but would like to know (for curiosity's sake ) how to do it in the for each style.

推荐答案

Collections.reverse 方法实际上返回一个新列表,其中原始列表的元素以相反的顺序复制到其中,因此这具有 O(n) 性能关于原始列表的大小.

The Collections.reverse method actually returns a new list with the elements of the original list copied into it in reverse order, so this has O(n) performance with regards to the size of the original list.

作为更有效的解决方案,您可以编写一个装饰器,将 List 的反向视图呈现为 Iterable.装饰器返回的迭代器将使用装饰列表的 ListIterator 以相反的顺序遍历元素.

As a more efficient solution, you could write a decorator that presents a reversed view of a List as an Iterable. The iterator returned by your decorator would use the ListIterator of the decorated list to walk over the elements in reverse order.

例如:

public class Reversed<T> implements Iterable<T> {
    private final List<T> original;

    public Reversed(List<T> original) {
        this.original = original;
    }

    public Iterator<T> iterator() {
        final ListIterator<T> i = original.listIterator(original.size());

        return new Iterator<T>() {
            public boolean hasNext() { return i.hasPrevious(); }
            public T next() { return i.previous(); }
            public void remove() { i.remove(); }
        };
    }

    public static <T> Reversed<T> reversed(List<T> original) {
        return new Reversed<T>(original);
    }
}

你会像这样使用它:

import static Reversed.reversed;

...

List<String> someStrings = getSomeStrings();
for (String s : reversed(someStrings)) {
    doSomethingWith(s);
}

这篇关于可以以相反的顺序为java中的每个循环做一个吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆