Filtering Sets in Java 8

June 14, 2018

Given a set, it's possible to filter it using a particular condition in Java 8.

Here's the set we're playing with:

Set<String> set = new HashSet<>();
set.add("ABC123"); 
set.add("ABC124");
set.add("ZZZ111");
set.add("ABC125");

I'm now looking to create a new set where the key in the set starts with AB. This can be done with:

String id = "AB";
Set<String> matchingKeys = set.stream().filter(p -> p.startsWith(id)).collect(Collectors.toSet());

for (String entry : matchingKeys){
  System.out.println(entry);
}

Tags: set java8 java filter