With Java 8 you can use the new removeIf method. Applied to your example:
Collection<Integer> coll = new ArrayList<>(); //populate coll.removeIf(i -> i == 5);
A simple test as example:
@Test public void testRemoveIfOneList() { List<String> outer = new ArrayList<>(); outer.add("one"); outer.add("two"); outer.add("three"); outer.removeIf(o -> o.length() == 3); assertEquals(1, outer.size()); }
It even works when you compare two lists and want to remove from both.
@Test public void testRemoveIfTwoLists() { List<String> outer = new ArrayList<>(); outer.add("one"); outer.add("two"); outer.add("three"); List<String> inner = new ArrayList<>(); inner.addAll(outer); // first, it removes from inner, and if anything is removed, then removeIf() returns true, // leading to removing from outer outer.removeIf(o -> inner.removeIf(i -> i.equals(o))); assertEquals(0, outer.size()); assertEquals(0, inner.size()); }
However, if one of the list has duplicates, make sure it's iterated in the inner loop, because for inner list, it will remove all elements meeting the criteria, but for outer list, when any element is removed, it will return immediately and stops checking.
This test will fail:
@Test public void testRemoveIfTwoListsInnerHasDuplicates() { List<String> outer = new ArrayList<>(); outer.add("one"); outer.add("one"); outer.add("two"); outer.add("two"); outer.add("three"); outer.add("three"); List<String> inner = new ArrayList<>(); inner.addAll(outer); // both have duplicates // remove all elements from inner(executed twice), then remove from outer // but only once! if anything is removed, it will return immediately!! outer.removeIf(o -> inner.removeIf(i -> i.equals(o))); assertEquals(0, inner.size()); // pass, inner all removed assertEquals(0, outer.size()); // will fail, outer has size = 3 }