Java:遍历列表列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2782893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 12:49:15  来源:igfitidea点击:

Java: iterating through list of lists?

javalistiteration

提问by hhh

The question but in C#.So does Java have C#'s command? I need it for Matches-SearchTerm-Files-relationship.

问题,但在 C# 中。那么Java有C#的命令吗?我需要它来匹配匹配-搜索词-文件-关系。

foreach(var i in BunchOfItems.SelectMany(k => k.Items)) {}

[Why not for-loops?]I have done such structures in nested for loops but they soon become bloated. So I prefer something more succint like the above.

[为什么不用 for 循环?]我在嵌套的 for 循环中做过这样的结构,但它们很快就会变得臃肿。所以我更喜欢像上面那样更简洁的东西。

public static Stack<Integer[]> getPrintPoss(String s,File f,Integer maxViewPerF)
{
    Stack<File> possPrint = new Stack<File>();
    Integer[] poss = new Integer[4]();
    int u,size;
    for(File f:files)
    { 
        size = f2S(f).length();
        u = Math.min(maxViewsPerF,size);
        for(int i=0; i<u;i++)
        {
           // Do something --- bloated, and soon out of control
           // wants more succintly

        }
    }
    return possPrint;
}

采纳答案by BalusC

Have about half a year patience until JDK7 is final which will include Closures. This provides simliar syntax and the same possibilities as LINQ which was demonstrated in the answer you're talking about.

有大约半年的耐心,直到 JDK7 是最终版本,其中将包括Closures。这提供了与 LINQ 相似的语法和相同的可能性,这在您所讨论的答案中得到了证明。

回答by someguy

for (List<Object> lo : list) {
    for (Object o : lo) {
        // etc etc
    }
}

I don't think there's a simpler solution.

我认为没有更简单的解决方案。

回答by bruno conde

I have my own version. Waiting desperately for Closuresin Java :

我有我自己的版本。拼命等待Java 中的闭包

public static <T, E> Iterable<T> transformMany(Iterable<E> iterable, Func<E, Iterable<T>> f) {
    if (null == iterable)
        throw new IllegalArgumentException("null iterable");
    if (null == f)
        throw new IllegalArgumentException("null f");

    return new TransformManyIterable<E, T>(iterable, f);
}

public interface Func<E, T> {
    T execute(E e);
}

public class TransformManyIterable<TOriginal, TResult> implements Iterable<TResult> {
    private Iterable<TOriginal> iterable;
    private Func<TOriginal, Iterable<TResult>> func;

    public TransformManyIterable(Iterable<TOriginal> iterable,
            Func<TOriginal, Iterable<TResult>> func) {
        super();
        this.iterable = iterable;
        this.func = func;
    }

    class TransformIterator implements Iterator<TResult> {
        private Iterator<TOriginal> iterator;
        private Iterator<TResult> currentIterator;

        public TransformIterator() {
            iterator = iterable.iterator();
        }

        @Override
        public boolean hasNext() {
            if (currentIterator != null && currentIterator.hasNext())
                return true;
            else {
                while (iterator.hasNext()) {
                    Iterable<TResult> iterable = func.execute(iterator.next());
                    if (iterable == null)
                        continue;
                    currentIterator = iterable.iterator();
                    if (currentIterator.hasNext())
                        return true;
                }
            }

            return false;
        }

        @Override
        public TResult next() {
            if (currentIterator != null && currentIterator.hasNext())
                return currentIterator.next();
            else {
                while (iterator.hasNext()) {
                    Iterable<TResult> iterable = func.execute(iterator.next());
                    if (iterable == null)
                        continue;
                    currentIterator = iterable.iterator();
                    if (currentIterator.hasNext())
                        return currentIterator.next();
                }
            }
            throw new NoSuchElementException();
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }

    @Override
    public Iterator<TResult> iterator() {
        return new TransformIterator();
    }

}

Usage:

用法:

    Iterable<SomeType> result = transformMany(input, new Func<InputType, Iterable<SomeType>>() {
        @Override
        public Iterable<SomeType> execute(InputType e) {
            return new ArrayList<SomeType>();
        }
    });

回答by Robin

The SelectMany method is part of LINQ which is .Net-specific. This questionasks about a LINQ equilvalent for java. Unfortunately, it doesn't look like there is a direct equivalent.

SelectMany 方法是特定于 .Net 的 LINQ 的一部分。这个问题询问了 java 的 LINQ 等价物。不幸的是,看起来没有直接的等价物。

回答by Kevin Bourrillion

If you can get the data into an Iterable<Iterable<T>>, then you can get from that to a flattened Iterable<T>using Guava's Iterables.concatmethod. If what you have is really an Iterable<S>, with some way to get from an Sto an Iterable<T>, well, then you have to first use Iterables.transformto view that as the Iterable<Iterable<T>>needed by concat.

如果您可以将数据放入 . Iterable<Iterable<T>>,那么您可以Iterable<T>使用 Guava 的Iterables.concat方法从该数据中获得扁平化。如果你有什么是真正的Iterable<S>,以某种方式从获取S到的Iterable<T>,好了,那么你必须先用Iterables.transform要查看的Iterable<Iterable<T>>需要的concat

All this will look a lot nicer if and when Java has something resembling closures, but at least today it's possible.

如果 Java 有类似闭包的东西,所有这些看起来都会好很多,但至少在今天这是可能的。

http://guava-libraries.googlecode.com

http://guava-libraries.googlecode.com

回答by Kyle Krull

With Java 8, you can say

使用 Java 8,你可以说

Collection bunchOfItems = ...;
bunchOfItems.stream().flatMap(k::getItems).forEach(i -> /* operate on i */);

or

或者

Item[] bunchOfItems = ...;
Stream.of(bunchOfItems).flatMap(k::getItems).forEach(i -> /* operate on i */);

depending upon whether you have a Collectionor an Array.

这取决于你是否有一个Collection或一个Array