Backend Development 6 min read

Understanding the Difference Between Java Stream filter and Collection removeIf

This article explains how Java 8's Stream filter method and Collection removeIf default method differ in functionality, predicate handling, and performance, and provides code examples and source snippets to illustrate their respective implementations and use cases.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
Understanding the Difference Between Java Stream filter and Collection removeIf

filter is a method of the Java 8 Stream interface with the signature Stream filter(Predicate predicate) , which returns a new stream containing only the elements that match the given predicate.

removeIf is a default method added to the Java 8 Collection interface, declared as default boolean removeIf(Predicate filter) , and it removes all elements of the collection that satisfy the supplied predicate.

Both methods can be used to filter or delete elements, but they differ in predicate semantics: removeIf deletes an element when the predicate evaluates to true (and keeps it when false ), whereas filter retains an element when the predicate evaluates to true (and discards it when false ).

From a performance perspective, removeIf returns a boolean immediately, while filter is an intermediate operation that requires a terminal operation (such as collect ) to produce a result; therefore, for simple deletion tasks, removeIf is generally faster.

Example comparison:

public static void main(String[] args) {
    List
list = new ArrayList<>(Arrays.asList(1,2,3,4,5));
    long start = System.currentTimeMillis();
    list.removeIf(a -> a.equals(2));
    System.out.println(System.currentTimeMillis() - start); // ~37-38 ms
}
public static void main(String[] args) {
    List
list = new ArrayList<>(Arrays.asList(1,2,3,4,5));
    long start = System.currentTimeMillis();
    list.stream().filter(a -> !a.equals(2)).collect(Collectors.toList());
    System.out.println(System.currentTimeMillis() - start); // ~41-44 ms
}

The source implementation of removeIf is a default method in the Collection interface. It iterates over the collection using an iterator, calls remove() on elements that satisfy the predicate, and returns true if any element was removed.

default boolean removeIf(Predicate
filter) {
    Objects.requireNonNull(filter);
    boolean removed = false;
    Iterator
each = iterator();
    while (each.hasNext()) {
        if (filter.test(each.next())) {
            each.remove();
            removed = true;
        }
    }
    return removed;
}

Each call to filter on a stream creates a new StatelessOp , which wraps a Sink that forwards elements downstream only when the predicate evaluates to true . The operation is part of the stream pipeline and is executed when a terminal operation is invoked.

public final Stream
filter(Predicate
predicate) {
    Objects.requireNonNull(predicate);
    return new StatelessOp
(this, StreamShape.REFERENCE, StreamOpFlag.NOT_SIZED) {
        @Override
        Sink
opWrapSink(int flags, Sink
sink) {
            return new Sink.ChainedReference
(sink) {
                @Override
                public void begin(long size) {
                    downstream.begin(-1);
                }
                @Override
                public void accept(P_OUT u) {
                    if (predicate.test(u))
                        downstream.accept(u);
                }
            };
        }
    };
}

In summary, removeIf is a straightforward collection operation that directly modifies the underlying data structure, while filter is a lazy, composable stream operation that forms part of a pipeline and requires a terminal operation to produce a result.

JavaPerformanceCollectionsStream APIfilterremoveIf
Java Architect Essentials
Written by

Java Architect Essentials

Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.