user414967 user414967 - 4 months ago 48
Java Question

java collection result designing

I am developing a small utility for collection filtering.
I have done the coding for that. What I am doing is iterating the original collection and find the filter matching and if any match is found then add the result to the new collection(result collection). And finally the result collection
is stored into the original collection. Is this good idea the collection result to store back to the orginal collection? I need to design this filtering framework in a fluent interface style. Please find the code below.


At first it's really bad practice modify original collection, because you can apply filter only once and you always should keep in mind that your original collection can be changed. It's highway to bugs.

Also use Predicate instead of Filter or make Filter implements Predicate, its more flexible and convenient way for filtering.


class Filter<T> implements Predicate<T> {}

You can create your filter then pass it to filter method easily.

Also keep in mind that your utility should be thread safe, better use this approach:

public final CollectionMapper<T> filter(Filter<T> filter) {
    Collection<T> result = new ArrayList<>();
    Iterator<T> iterator = orginal.iterator();
    while (iterator.hasNext()) {
        T t =;

        if (filter.match(t)) {


    return new CollectionMapper<>(result);