Nick
Nick

Reputation: 168

Unite Collection of Collections into Collection in a method in Java

I've created a Collection class that extends ArrayList to add some useful methods. It looks like this:

public class Collection<T> extends ArrayList<T> {
    //some methods...
}

I want to be able to unite a Collection of Collections to a single Collection, like this:

{{1, 2}, {2,3}, {1}, {2}, {}} -> {1, 2, 2, 3, 1, 2}

I have an idea of how a static method should look like:

public static<E> Collection<E> unite(Collection<Collection<E>> arr) {
    Collection<E> newCollection = new Collection<>();

    for(Collection<E> element : arr) {
        newCollection.merge(element);
    }

    return newCollection;
}

But I don't know how to make this method non-static(so that it accepts no arguments, like this:

Collection<E> list = listOfLists.unite();

). Is that even possible? If it is, can you please help me with it?

Upvotes: 3

Views: 2290

Answers (3)

Lino
Lino

Reputation: 19926

A way would be to explicitly declare the type parameter to be a List<E> and then its pretty much straight forward:

class NestedList<E> extends ArrayList<List<E>> {
    public List<E> flatten() {
        return stream()
            .flatMap(Collection::stream)
            .collect(Collectors.toList());
    }
}

Upvotes: 0

ernest_k
ernest_k

Reputation: 45319

It doesn't make sense to do it for any concrete type T. If T is not of a Collection type, then unite() is an irrelevant method (if you have a ArrayListModified<Double>, for example, you can't flatten it because that's absurd).

So you either have to make T bounded to collections:

public class ArrayListModified<E, T extends Collection<E>> extends ArrayList<T> {

    public Collection<E> unite() {
        Collection<E> newCollection = new ArrayList<>();

        for (Collection<E> element : this) {
            newCollection.addAll(element);
        }

        return newCollection;
    }
}

Or use a static method that takes one ArrayListModified<ArrayListModified<E>> parameter just as in your current implementation (though it wouldn't be required to be static).

Upvotes: 2

Gene.Qu
Gene.Qu

Reputation: 1

try use '?' instead of 'E'. Idk whether im right.

public Collection<?> unite(Collection<Collection<?>> collection) {
        Collection<?> newCollection = new Collection<>();

        for(Collection<?> element : collection) {
            newCollection.merge(element);
        }

        return newCollection;
    }

Upvotes: -1

Related Questions