2

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
  • 1
    Sounds like homework for recursion. There is no call that does it for you, but coding it is pretty simple. Commented Oct 20, 2010 at 7:58

2 Answers 2

3
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;
}
2
  • Can you please give an example of how to properly call this method? I haven't used the ? with java generics before and I am pretty sure (despite googling) I have still not gotten it right. Commented Jan 22, 2013 at 1:03
  • 1
    @Nick: You can pass any list there, but you get back List of "unknowns". This method cannot promise any more than that. If you are sure that elements of the input list are either T or List<T>, you can then cast resulting list back to (List<T>) (you will get compiler warning about that). Otherwise, List<?> is similar to List of Objects, except you can only get elements from it. If you change method return type to List<Object> it will still work correctly, and it will allow you to modify resulting list without more casting. Commented Jan 22, 2013 at 9:54
2

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

2
  • 2
    Is there also one in Guava or Commons Collections (for people who are not groovy enough)?
    – Thilo
    Commented Oct 20, 2010 at 8:17
  • 2
    @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
    Commented Oct 20, 2010 at 8:19

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.