Sunday, January 4, 2015

Google Gauva API in a one glance: ObjectArrays, Ranges, Stopwatch

ObjectArrays : operate on arrays of any type and allows to concatenate arrays and add single element before first or after last position.
Ranges : Ranges and Range classes are used to define ranges and then checking if a given object is contained within defined range.
Stopwatch : to measure the elapsed time between a operation.
lets test these out using sample code
/**
*
*/
package com.rajkrrsingh.test.guava;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import com.google.common.base.Predicate;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Iterables;
import com.google.common.collect.ObjectArrays;
import com.google.common.collect.Range;
import com.google.common.collect.Ranges;

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

public static void main(String[] args) {
objectArrayDemo();
rangesDemo();
stopWatchDemo();
}

// ObjectArrays to operate on array of given type,concanate two arrays, add element on first and last index
public static void objectArrayDemo(){
String[] arr1 = new String[]{"ele1","ele2","ele3"};
String[] arr2 = new String[]{"ele11","ele22"};

String[] conArray = ObjectArrays.concat(arr1, arr2, String.class);
System.out.println(Arrays.toString(conArray));

String[] arr3= ObjectArrays.concat(arr1, "ele4");
System.out.println(Arrays.toString(arr3));

String[] arr4= ObjectArrays.concat("ele00", arr2);
System.out.println(Arrays.toString(arr4));
}

// Ranges to define ranges and then identify element is contained within the range or not
public static void rangesDemo(){
Range<Integer> closedRange = Ranges.closed(1, 10);
System.out.println(closedRange.contains(10));
System.out.println(closedRange.contains(11));

Range<Integer> rightOpenRange = Ranges.closedOpen(1, 10);
System.out.println(rightOpenRange.contains(10));
}

// demonstation of stopwatch
public static void stopWatchDemo(){
final Stopwatch stopwatch = new Stopwatch();
stopwatch.start();

//Sleep for few random milliseconds.
try {
Thread.sleep(new Random().nextInt(1000));
} catch (final InterruptedException interruptedException) {
interruptedException.printStackTrace();
}

stopwatch.stop(); //optional

System.out.println("Elapsed time ==> " + stopwatch);
System.out.println("Elapsed time in Nanoseconds ==> " + stopwatch.elapsedTime(TimeUnit.NANOSECONDS));
System.out.println("Elapsed time in Microseconds ==> " + stopwatch.elapsedTime(TimeUnit.MICROSECONDS));
System.out.println("Elapsed time in Milliseconds ==> " + stopwatch.elapsedTime(TimeUnit.MILLISECONDS));
}

}
Post a Comment