sebastiandaschner blog


Remove collection elements that match a criteria

saturday, december 02, 2017

Since JDK 1.8 there is the handy new Collection#removeIf method that takes a Predicate<T> and removes all elements in the collection that matches these:

List<String> coffeeShops = new ArrayList<>();
coffeeShops.add("Blue Bottle Coffee");
coffeeShops.add("Four Barrel Coffee");
coffeeShops.add("Coffee Collective");
coffeeShops.add("Obscura Coffee Roasters");
coffeeShops.add("About Life");

assertThat(coffeeShops.size(), is(5));

coffeeShops.removeIf(t -> t.contains("Coffee"));

assertThat(coffeeShops.size(), is(1));

The removeIf invocation removes all elements that match the given Predicate; the example collection retains the element About Life.

This post was reposted from my newsletter issue 001.

 

Found the post useful? Subscribe to my newsletter for more free content, tips and tricks on IT & Java: