Sunday, January 4, 2015

Google Gauva API in a one glance: Iterables

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;


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

public static void main(String[] args) {

// 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>() {

public boolean apply(Employee emp) {
return emp.getEmpid().length()==3;
System.out.println("all emp of empid of length 3");
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){


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

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);

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