Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: iterating through list of lists?

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

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.

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;
}
like image 682
hhh Avatar asked May 06 '10 16:05

hhh


3 Answers

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

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

like image 192
someguy Avatar answered Sep 28 '22 14:09

someguy


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.concat method. If what you have is really an Iterable<S>, with some way to get from an S to an Iterable<T>, well, then you have to first use Iterables.transform to view that as the Iterable<Iterable<T>> needed by concat.

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

http://guava-libraries.googlecode.com

like image 24
Kevin Bourrillion Avatar answered Sep 28 '22 14:09

Kevin Bourrillion


With Java 8, you can say

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 Collection or an Array.

like image 44
Kyle Krull Avatar answered Sep 28 '22 14:09

Kyle Krull