Member-only story

Java: Filter a Collection

Leo N
2 min readJun 16, 2019

--

https://dzone.com/articles/an-introduction-to-the-java-collections-framework

Imagine we have a simple Java class:

public class Animal {
private int money;
private Gender sex;

}

enum Gender { MALE, FEMALE };

And that you have a Collection of Animal objects, such as the following one:

Animal a1 = new Animal(35, Gender.MALE);
Animal a2 = new Animal(30, Gender.MALE);
Animal a3 = new Animal(25, Gender.FEMALE);
Animal a4 = new Animal(15, Gender.FEMALE);

List<Animal> animals = Arrays.asList(a1,a2,a3,a4);

Use plain Java, like tough people do

List<Animal> result = new ArrayList<Animal>();
for (Animal item : animals) {
if (item.getMoney() > 21 && item.getGender() == Gender.MALE) {
result.add(item);
}
}

// now result contains the filtered collection

Filtering by predicate

The second option is what Commons Collections and Guava propose, and that I think should have been part of the Java core at least since Java 5.

public interface Predicate<T> { boolean apply(T type); }

public static <T> Collection<T> filter(Collection<T> col, Predicate<T> predicate) {
Collection<T> result = new ArrayList<T>();
for (T element: col) {
if (predicate.apply(element)) {
result.add(element);
}
}
return result;
}

--

--

Leo N
Leo N

Written by Leo N

🇻🇳 🇸🇬 🇲🇾 🇦🇺 🇹🇭 Engineer @ GXS Bank, Singapore | MSc 🎓 | Technical Writer . https://github.com/nphausg

No responses yet