Wednesday, December 03, 2008

Filtering in Java

I find the below piece of code pretty useful for filtering purposes in java. I use the apache Commons collection library for this purpose. In the below code snippet, I am filtering on id in the model Data present in the List. After running this code snippet, the 'list' will contain only those Data Objects that satisfy the filter criteria, in this case that will be 'userId = Id'. Predicate defines the filter criteria in the snippet below.

public void filterOnId(String Id,List<Data> list){ 
final StringBuilder string = new StringBuilder(Id);
Predicate predicate = new Predicate(){
public boolean evaluate(Object object) {
boolean returnValue = false;
if(object instanceof Data){
Data vo = (Data)object;
returnValue = vo.getUserId().compareTo(string.toString())==0?true:false;
return returnValue;
CollectionUtils.filter(list, predicate);

No comments:

Post a Comment