Just thought that I'd post a Java 8 solution that may help someone in the future. Java 8 Streams offers a bunch of nice methods such as filter
and collect
. The filter
method simply filters out the elements from the stream that should be carried on to the next step. The collect
method combines elements to a Collection
of some sort or a Map
.
// The data to filter
final Set<String> strings =
new HashSet<>(Arrays.asList("a", "ab", "abc", "abcd"));
// Now, stream it!
final Set<String> odds =
strings.stream()
.filter(s -> s.length() % 2 != 0) // keep the odds
.collect(Collectors.toSet()); // collect to a new set
This does not actually modify the original collection but creates a new Set
containing the String
objects of odd length.
For more reading on Java 8 Streams, checkout this excellent tutorial from Oracle or the great JavaDocs.