Over a million developers have joined DZone.

Java Holiday Calendar 2016 (Day 4): Use RemoveIf in Java Collections

DZone's Guide to

Java Holiday Calendar 2016 (Day 4): Use RemoveIf in Java Collections

If you want to remove elements from a collection quick, fast, and in a hurry, take a look at removeIf(), which should save you ton of time over manual iterations.

· Java Zone
Free Resource

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

Image title

Today's tip is to use the removeIf() method (that all collection classes like List have) rather than manually iterating over the elements and removing them. For large data sets, removeIf() can be orders of magnitudes faster than other methods. It also looks much better in your code. Why? Read more here and see for yourself! In the meantime, let's see how to put it to use.

Do This

items.removeIf(i -> predicate(i));

Don't Do This:

for (Iterator it = items.iterator(); it.hasNext();) {  
    if (predicate(it.next())) {

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.

Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.

java ,removeif ,java performance ,collections

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}