Day 4, Java Holiday Calendar 2016, RemoveIf

by Per Minborg

on December 4, 2016

4. Use RemoveIf in Java Collections



Today's tips is to use the removeIf() method (that all collection classes like List have) rather than manually iterating over the elements and remove them. For large data sets, removeIf() can be orders of magnitudes faster than other ways. It also looks much better in your code. Why? Read more here and see for your self!

Do This:

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

Don't Do This:

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

Read more in the original article at http://javadeau.lawesson.se/2016/09/java-8-removeif.html

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

About

Per Minborg

Per Minborg is a Palo Alto based developer and architect, currently serving as CTO at Speedment, Inc. He is a regular speaker at various conferences e.g. JavaOne, DevNexus, Jdays, JUGs and Meetups. Per has 15+ US patent applications and invention disclosures. He is a JavaOne alumni and co-author of the publication “Modern Java”.