Filtering a List in Java






4.80/5 (4 votes)
Filtering a List of custom instances
Introduction
The main purpose of this tip is to filter any List
containing custom instances. Suppose you have a list of 100 Employees and you want a filtered list on the basis of names starting with "John
". May be, there are lots of existing ways to implement this. However, I have tried to implement and want to share what I have got.
Implementation
To implement filtering, we need an interface called Filter
, which basically carries the filter logic.
interface Filter<T,E> {
public boolean isMatched(T object, E text);
}
And a FilterList
class which returns the FilteredList
.
public class FilterList<E> {
public <T> List filterList(List<T> originalList, Filter filter, E text) {
List<T> filterList = new ArrayList<T>();
for (T object : originalList) {
if (filter.isMatched(object, text)) {
filterList.add(object);
} else {
continue;
}
}
return filterList;
}
}
And here is our simple Employee
bean class.
public class Employee {
private String name;
public Employee(String name) {
setName(name);
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
}
Now we have to create our filter first. Here is the FilterListTest
class to test the FilterList
.
public class FilterListTest {
public static void main(String main[]) {
List<Employee> empList = new ArrayList<Employee>();
//Testing value
Employee emp = new Employee("John Miller");
empList.add(emp);
for (int i = 0; i < 5; i++) {
emp = new Employee("John Miller");
empList.add(emp);
emp = new Employee("Miller John");
empList.add(emp);
}
/**
** Creating Filter Logic
**/
Filter<Employee,String> filter = new Filter<Employee,String>() {
public boolean isMatched(Employee object, String text) {
return object.getName().startsWith(String.valueOf(text));
}
};
/**
* Pass filter to filter the original list
*/
List<Employee> sortEmpList = new FilterList().filterList(empList, filter, "John");
}
}
All done. Your Employee
list is now filtered with "John
".