Derek
Derek

Reputation: 853

Java ArrayList: Merging ArrayLists within ArrayLists to create one ArrayList

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"}

Upvotes: 2

Views: 6439

Answers (2)

haylem
haylem

Reputation: 22663

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

Upvotes: 2

Peter Štibraný
Peter Štibraný

Reputation: 32893

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;
}

Upvotes: 3

Related Questions