removeIf and bulk operations
Delete, keep and rewrite whole collections in one call instead of writing a loop.
Open this lesson in the learning hubKey points
removeIf(pred)deletes every match in a single safe pass and returns whether anything changed.removeAll,retainAllandaddAllgive you difference, intersection and union of two collections.replaceAll(fn)rewrites every element in place; on a map it takes both key and value.- Map views are live, so
map.values().removeIf(v -> v == 0)deletes those entries from the map itself. - Bulk ops call
containson their argument repeatedly. Pass aSet, not a bigList, to stay fast.
Example
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("ann", "bob", "cyd", "dee", "eli"));
names.removeIf(n -> n.startsWith("b") || n.startsWith("d"));
System.out.println("removeIf : " + names);
List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
nums.removeAll(List.of(2, 4));
System.out.println("removeAll : " + nums);
nums.retainAll(List.of(1, 3, 9));
System.out.println("retainAll : " + nums);
nums.replaceAll(x -> x * 10);
System.out.println("replaceAll : " + nums);
Map<String, Integer> stock = new LinkedHashMap<>();
stock.put("nuts", 0);
stock.put("bolts", 7);
stock.put("nails", 0);
stock.values().removeIf(v -> v == 0);
System.out.println("values().removeIf : " + stock + " (view writes through)");
Set<String> a = new LinkedHashSet<>(List.of("x", "y", "z"));
Set<String> b = Set.of("y", "z", "w");
Set<String> union = new LinkedHashSet<>(a);
union.addAll(b);
Set<String> intersect = new LinkedHashSet<>(a);
intersect.retainAll(b);
Set<String> difference = new LinkedHashSet<>(a);
difference.removeAll(b);
System.out.println("union : " + union);
System.out.println("intersection : " + intersect);
System.out.println("difference : " + difference);
}
}
If your loop only deletes, filters or rewrites, a bulk method already does it in one line.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Collections course, and every lesson in it is listed on the Collections contents page.