Sunday, January 4, 2015

Google Gauva API in a one glance: Predicate

  • Predicate<T>, which has the single method boolean apply(T input). Instances of Predicate are generally expected to be side-effect-free and consistent with equals.

@GwtCompatible
public interface Predicate<T>
Determines a true or false value for a given input.The Predicates class provides common predicates and related utilities.
lets see how to use predicate to filter out some elements from the given collection. create a tester class as follows and follow along my blog post to get Employee Class
/**
*
*/
package com.rajkrrsingh.test.guava;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2;
import com.google.common.collect.Iterables;

/**
* @author rks
* @04-Jan-2015
*/
public class GuavaPredicateDemo {

public static void main(String[] args) {
pridcateDemo();
}

public static void pridcateDemo(){
List<Employee> empList = Employee.getEmployeeList();

Predicate<Employee> ageOver30 = new Predicate<Employee>() {

@Override
public boolean apply(Employee emp) {
if(emp.getAge()>30){
return true;
}
return false;
}
};

Predicate<Employee> slryLt10000 = new Predicate<Employee>() {

@Override
public boolean apply(Employee emp) {
if(emp.getSalary()<10000)
return true;
return false;
}
};

System.out.println("**** print emp name whose age is greater than 30 ****");
Iterator<Employee> filterAgeIterator= Iterables.filter(empList, ageOver30).iterator();
while(filterAgeIterator.hasNext()){
System.out.println(filterAgeIterator.next().getEmpName());
}

System.out.println("**** print emp name whose age is greater than 30 and salary is less than 10000 ****");
Iterator<Employee> filterOnAgeAndSal= Iterables.filter(empList, Predicates.and(ageOver30, slryLt10000)).iterator();
while(filterOnAgeAndSal.hasNext()){
System.out.println(filterOnAgeAndSal.next().getEmpName());
}

System.out.println("**** print emp name whose age is greater than 30 OR salary is less than 10000 ****");
Iterator<Employee> filterOnAgeORSal= Iterables.filter(empList, Predicates.or(ageOver30, slryLt10000)).iterator();
while(filterOnAgeORSal.hasNext()){
System.out.println(filterOnAgeORSal.next().getEmpName());
}
}
}
Please follow my comments in the code to relate with the output
**** print emp name whose age is greater than 30 ****
RKS
Derek
Nick
**** print emp name whose age is greater than 30 and salary is less than 10000 ****
Nick
**** print emp name whose age is greater than 30 OR salary is less than 10000 ****
RKS
Derek
Jack
Nick


No comments: