fbpx

retainIf and removeIf for Java Collections

Iterate over Java collection classes to conditionally retain or remove values from the collection.

CollectionUtil.retainIf(list, element -> element > 5);

Retains all elements in the collection that have a value greater than 5.


CollectionUtil.removeIf(list, element -> element > 5);

Removes all elements from the list that have a value greater than 5.


The CollectionUtil class is available as part of BlobCity java-commons open source distribution of useful Java utilities.

https://github.com/blobcity/java-commons

Jar file: https://github.com/blobcity/java-commons/tree/master/target 

Complete Implementation

List<Integer> list1 = new ArrayList<>(Arrays.asList(1,5,10,30,4,8,11));
List<Integer> list2 = new ArrayList<>(Arrays.asList(1,5,10,30,4,8,11));

/* Retains all elements in list that have a value > 5 */
CollectionUtil.retainIf(list1, element -> element > 5);

System.out.println("List 1");
list1.forEach(System.out::println);

/* Removes all elements in list that have a value > 5 */
CollectionUtil.removeIf(list2, element -> element > 5);

System.out.println("\nList 2");
list2.forEach(System.out::println);

Output

List 1
10
30
8
11

List 2
1
5
4
%d bloggers like this: