Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

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())) {
        it.remove();    
    }
}


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

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:
java ,removeif ,java performance ,collections

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}