tags:

views:

70

answers:

2

Hello again, I've looked around but I can't seem to find an API call that does the following: I need to merge all ArrayLists in an ArrayList to form one ArrayList with all the elements from all the sub-ArrayLists, if that makes sense.

Here's an example:

{"It's", "a", {"small", "world, "after"}, {"all"}} becomes {"It's", "a", "small", "world", "after", "all"}

+1  A: 
public List<?> flatten(List<?> input) {
    List<Object> result = new ArrayList<Object>();

    for (Object o: input) {
        if (o instanceof List<?>) {
            result.addAll(flatten((List<?>) o));
        } else {
            result.add(o);
        }
    }

    return result;
}
Peter Štibraný
+1  A: 

To build on top of Thilo's answer, and to avoid re-implementing your own, consider Groovy's Collection.flatten()

haylem
Is there also one in Guava or Commons Collections (for people who are not groovy enough)?
Thilo
@Thilo: guess what, I actually had a look too, you read my mind! Surprisingly, I couldn't find any, though I would have expected Guava to have it somewhere. Apache Commons Collections have a FlatMap or something, but no "flattenizer" that I know of.
haylem