Sunday, January 4, 2015

Google Gauva API in a one glance: Iterables


@GwtCompatible(emulated=true)
public final class Iterables
extends Object
This class contains static utility methods that operate on or return objects of type Iterable. Except as noted, each method has a corresponding Iterator-based method in the Iterators class.Performance notes: Unless otherwise noted, all of the iterables produced in this class are lazy, which means that their iterators only advance the backing iteration when absolutely necessary.

lets see how iterables work using the following sample code, you can follow the blog entry for Employee class implementation.
/**
*
*/
package com.rajkrrsingh.test.guava;

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

import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;

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

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

// working with iterables
public static void iterablesDemo(){

//all() method allows to check if defined condition is satisfied by all elements from Collection
boolean flag = Iterables.all(Employee.getEmployeeList(), new Predicate<Employee>() {

@Override
public boolean apply(Employee emp) {
return emp.getEmpid().length()==3;
}
});
if(flag){
System.out.println("all emp of empid of length 3");
}else{
System.out.println("not all emp of empid of length 3");
}

// iterate in infinite cycle
int iterateCount=0;
Iterator<Employee> itr = Iterables.cycle(Employee.getEmployeeList()).iterator();
while(itr.hasNext() && iterateCount<20){
System.out.println(itr.next());
iterateCount++;

}

// counts number of elemens in the Collection
int count = Iterables.frequency(Employee.getEmployeeList(), null);
System.out.println(count);

//getFirst
System.out.println(Iterables.getFirst(Employee.getEmployeeList(), new Employee()));

// getLast
System.out.println(Iterables.getLast(Employee.getEmployeeList(), new Employee()));

// partition a list
Iterable<List<Employee>> iterables = Iterables.partition(Employee.getEmployeeList(), 2);
System.out.println(Iterables.size(iterables));

// iterables to array
Employee[] empArr = Iterables.toArray(Employee.getEmployeeList(), Employee.class);
System.out.println(empArr.length);
}
}
Post a Comment