Conditionally remove elements from a List in Java 8

Java 8 introduces a new method available for Collection types: removeif(). It accepts a predicate which defines the condition on which the elements should be removed. It returns a boolean where a true response means that at least one item has been removed and false otherwise:

Collection<String> stringStack = new Stack<>();
stringStack.add("Hello");
stringStack.add("my");
stringStack.add("dear");
stringStack.add("world");
        
stringStack.removeIf(s -> s.contains("ll"));

The above example will remove “Hello” from the list stack.

Note that not all collections support item removal. In that case the method will throw an UnsupportedOperationException in case an attempt is made to remove a matching element. The ArrayList is one such collection:

Collection<String> asList = Arrays.asList("hello", "my", "dear", "world");
asList.removeIf(s -> s.contains("ll"));

This will throw an exception unfortunately as the Array.asList method returns an ArrayList of type java.util.Arrays.ArrayList (which is read only and fixed size) and not the classic java.util.ArrayList (resizable and item-removable) – based on a comment by Juanito below.

View all posts related to Java here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

8 Responses to Conditionally remove elements from a List in Java 8

  1. Cristina says:

    Hi,

    Can I remove using two conditions? Do I have to create a distinct Predicate or merely I can use && between the conditions?

    Thanks,
    Cristina

    • Andras Nemes says:

      Hello Cristina, I’m not sure I follow. Where do you see two conditions in this post? //Andras

      • Cristina says:

        Hi Andras,

        Well starting from your example I was wondering if I can use two conditions. I created two distinct predicates and I used “and” function. My problem is solved.

        Regards,
        Cristina

  2. I think you should state more clearly that the type returned for the method Arrays.asList is of type java.util.Arrays.ArrayList (which is read only and fixed size) and not the classical java.util.ArrayList (resizable and item-removable)

  3. Oleksii says:

    Thx Andras,
    nice example which helped me to tackle a problem of removing of an element from TreeSet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: