This example will demonstrates how to filter a collection by a java class type using java, java 8, guava and apache commons.
Straight up Java
Until Java 8, the jdk did not have a way to filter a collection unless you iterate over the collection and then apply criteria. In the snippet below, we will use a enhanced for loop using the instanceOf keyword to check if it is of class String.
Java 8 introduced the stream api which allows you to write powerful code in just a few lines. Streams filter is an intermediate operation that will return a stream consisting of the elements that match the specified predicate. In the snippet below, through a lambda expression we will create a java predicate that will filter elements where the class type equals a string.
Similar to java and guava predicate, apache commons has a predicate class as well. Below we will call CollectionsUtils.filter passing it a predicate that will return true if the object is of class type String and it will remove the elements where it doesn't match this criteria.