Guava – Quick Guide

Guava – Quick Guide

Guava – Overview

What is Guava?

Guava is an open source, Java-based library and contains many
core libraries of Google, which are being used in many of their
projects. It facilitates best coding practices and helps reduce
coding errors. It provides utility methods for collections,
caching, primitives support, concurrency, common annotations,
string processing, I/O, and validations.

Benefits of Guava

  • Standardized − The Guava library is managed by Google.
  • Efficient − It is a reliable, fast, and efficient
    extension to the Java standard library.
  • Optimized − The library is highly optimized.
  • Functional Programming − It adds functional processing
    capability to Java.
  • Utilities − It provides many utility classes which are
    regularly required in programming application development.
  • Validation − It provides a standard failsafe
    validation mechanism.
  • Best Practices − It emphasizes on best practices.
Consider the following code snippet.
public class GuavaTester {
public static void main(String args[]) {
GuavaTester guavaTester = new GuavaTester();

Integer a = null;
Integer b = new Integer(10);
System.out.println(guavaTester.sum(a,b));
}

public Integer sum(Integer a, Integer b) {
return a + b;
}
}
Run the program to get the following result.
Exception in thread "main" java.lang.NullPointerException
at GuavaTester.sum(GuavaTester.java:13)
at GuavaTester.main(GuavaTester.java:9)
Following are the problems with the code.
  • sum() is not taking care of any of the parameters to be
    passed as null.
  • caller function is also not worried about passing a null to
    the sum() method accidently.
  • When the program runs, NullPointerException occurs.
In order to avoid the above problems, null check is to be made in
each and every place where such problems are present.
Let’s see the use of Optional, a Guava provided Utility class, to
solve the above problems in a standardized way.
import com.google.common.base.Optional;

public class GuavaTester {
public static void main(String args[]) {
GuavaTester guavaTester = new GuavaTester();

Integer invalidInput = null;
Optional<Integer> a = Optional.of(invalidInput);
Optional<Integer> b = Optional.of(new Integer(10));
System.out.println(guavaTester.sum(a,b));
}

public Integer sum(Optional<Integer> a, Optional<Integer> b) {
return a.get() + b.get();
}
}
Run the program to get the following result.
Exception in thread "main" java.lang.NullPointerException
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:210)
at com.google.common.base.Optional.of(Optional.java:85)
at GuavaTester.main(GuavaTester.java:8)
Let’s understand the important concepts of the above program.
  • Optional − A utility class, to make the code use the
    null properly.
  • Optional.of − It returns the instance of Optional
    class to be used as a parameter. It checks the value passed,
    not to be ‘null’.
  • Optional.get − It gets the value of the input stored
    in the Optional class.
Using the Optional class, you can check whether the caller method
is passing a proper parameter or not.

Guava – Environment Setup

Local Environment Setup

If you are still willing to set up your environment for Java
programming language, then this section guides you on how to
download and set up Java on your machine. Please follow the steps
mentioned below to set up the environment.
Java SE is freely available from the link . So you download a
version based on your operating system.
Follow the instructions to download Java and run the .exe
to install Java on your machine. Once you have installed Java on
your machine, you would need to set environment variables to
point to correct installation directories −

Setting up the Path for Windows 2000/XP

We are assuming that you have installed Java in c:Program
Filesjavajdk
 directory −
  • Right-click on ‘My Computer’ and select ‘Properties’.
  • Click on the ‘Environment variables’ button under the
    ‘Advanced’ tab.
  • Now, alter the ‘Path’ variable so that it also contains the
    path to the Java executable. Example, if the path is
    currently set to ‘C:WINDOWSSYSTEM32’, then change your path
    to read ‘C:WINDOWSSYSTEM32;c:Program Filesjavajdkbin’.

Setting up the Path for Windows 95/98/ME

We are assuming that you have installed Java in c:Program
Filesjavajdk
 directory −
  • Edit the ‘C:autoexec.bat’ file and add the following line at
    the end − ‘SET PATH=%PATH%;C:Program Filesjavajdkbin’

Setting up the Path for Linux, UNIX, Solaris, FreeBSD

Environment variable PATH should be set to point to where the
Java binaries have been installed. Refer to your shell
documentation if you have trouble doing this.
Example, if you use bash as your shell, then you would add the
following line to the end of your ‘.bashrc: export
PATH=/path/to/java:$PATH’

Popular Java Editors

To write your Java programs, you need a text editor. There are
many sophisticated IDEs available in the market. But for now, you
can consider one of the following −
  • Notepad − On Windows machine you can use any simple
    text editor like Notepad (Recommended for this tutorial),
    TextPad.
  • Netbeans − It is a Java IDE that is open-source and
    free which can be downloaded from .
  • Eclipse − It is also a Java IDE developed by the
    eclipse open-source community and can be downloaded from .

Download Guava Archive

Download the latest version of Guava jar file from . At the time
of writing this tutorial, we have downloaded
guava-18.0.jar and copied it into C:>Guava folder.
OSARCHIVE NAME
Windowsguava-18.0.jar
Linuxguava-18.0.jar
Macguava-18.0.jar

Set Guava Environment

Set the Guava_HOME environment variable to point to the
base directory location where Guava jar is stored on your
machine. Assuming, we’ve extracted guava-18.0.jar in Guava folder
on various Operating Systems as follows.
OSOUTPUT
WindowsSet the environment variable Guava_HOME to C:Guava
Linuxexport Guava_HOME=/usr/local/Guava
Macexport Guava_HOME=/Library/Guava

Set CLASSPATH Variable

Set the CLASSPATH environment variable to point to the
Guava jar location. Assuming, you have stored guava-18.0.jar in
Guava folder on various Operating Systems as follows.
OSOUTPUT
WindowsSet the environment variable CLASSPATH to
%CLASSPATH%;%Guava_HOME%guava-18.0.jar;.;
Linuxexport CLASSPATH=$CLASSPATH:$Guava_HOME/guava-18.0.jar:.
Macexport CLASSPATH=$CLASSPATH:$Guava_HOME/guava-18.0.jar:.

Guava – Optional Class

Optional is an immutable object used to contain a not-null
object. Optional object is used to represent null with absent
value. This class has various utility methods to facilitate the
code to handle values as available or not available instead of
checking null values.

Class Declaration

Following is the declaration for
com.google.common.base.Optional<T> class −
@GwtCompatible(serializable = true)
public abstract class Optional<T>
extends Object
implements Serializable

Class Methods

SR.NOMETHOD & DESCRIPTION
1
static <T> Optional<T> absent()
Returns an Optional instance with no contained reference.
2
abstract Set<T> asSet()
Returns an immutable singleton Set whose only element is
the contained instance if it is present; an empty immutable
Set otherwise.
3
abstract boolean equals(Object object)
Returns true if object is an Optional instance, and either
the contained references are equal to each other or both
are absent.
4
static <T> Optional<T> fromNullable(T
nullableReference)
If nullableReference is non-null, returns an Optional
instance containing that reference; otherwise returns
absent().
5
abstract T get()
Returns the contained instance, which must be present.
6
abstract int hashCode()
Returns a hash code for this instance.
7
abstract boolean isPresent()
Returns true if this holder contains a (non-null) instance.
8
static <T> Optional<T> of(T reference)
Returns an Optional instance containing the given non-null
reference.
9
abstract Optional<T> or(Optional<? extends
T> secondChoice)
Returns this Optional if it has a value present;
secondChoice otherwise.
10
abstract T or(Supplier<? extends T> supplier)
Returns the contained instance if it is present;
supplier.get() otherwise.
11
abstract T or(T defaultValue)
Returns the contained instance if it is present;
defaultValue otherwise.
12
abstract T orNull()
Returns the contained instance if it is present; null
otherwise.
13
static <T> Iterable<T>
presentInstances(Iterable<? extends Optional<?
extends T>> optionals)
Returns the value of each present instance from the
supplied optionals, in order, skipping over occurrences of
absent().
14
abstract String toString()
Returns a string representation for this instance.
15
abstract <V> Optional<V>
transform(Function<? super T,V> function)
If the instance is present, it is transformed with the
given Function; otherwise, absent() is returned.

Methods Inherited

This class inherits methods from the following class −
  • java.lang.Object

Example of Optional Class

Create the following java program using any editor of your choice
in say C:/> Guava.

GuavaTester.java

import com.google.common.base.Optional;

public class GuavaTester {
public static void main(String args[]) {
GuavaTester guavaTester = new GuavaTester();

Integer value1 = null;
Integer value2 = new Integer(10);

//Optional.fromNullable - allows passed parameter to be null.
Optional<Integer> a = Optional.fromNullable(value1);

//Optional.of - throws NullPointerException if passed parameter is null
Optional<Integer> b = Optional.of(value2);

System.out.println(guavaTester.sum(a,b));
}

public Integer sum(Optional<Integer> a, Optional<Integer> b) {
//Optional.isPresent - checks the value is present or not
System.out.println("First parameter is present: " + a.isPresent());

System.out.println("Second parameter is present: " + b.isPresent());

//Optional.or - returns the value if present otherwise returns
//the default value passed.
Integer value1 = a.or(new Integer(0));

//Optional.get - gets the value, value should be present
Integer value2 = b.get();

return value1 + value2;
}
}

Verify the Result

Compile the class using javac compiler as follows −
C:Guava>javac GuavaTester.java
Now run the GuavaTester to see the result.
C:Guava>java GuavaTester
See the result.
First parameter is present: false
Second parameter is present: true
10

Guava – Preconditions Class

Preconditions provide static methods to check that a method or a
constructor is invoked with proper parameter or not. It checks
the pre-conditions. Its methods throw IllegalArgumentException on
failure.

Class Declaration

Following is the declaration for
com.google.common.base.Preconditions class −
@GwtCompatible
public final class Preconditions
extends Object

Class Methods

SR.NOMETHOD & DESCRIPTION
1
static void checkArgument(boolean expression)
Ensures the truth of an expression involving one or more
parameters to the calling method.
2
static void checkArgument(boolean expression, Object
errorMessage)
Ensures the truth of an expression involving one or more
parameters to the calling method.
3
static void checkArgument(boolean expression, String
errorMessageTemplate, Object. errorMessageArgs)
Ensures the truth of an expression involving one or more
parameters to the calling method.
4
static int checkElementIndex(int index, int size)
Ensures that index specifies a valid element in an array,
list or a string of size.
5
static int checkElementIndex(int index, int size, String
desc)
Ensures that index specifies a valid element in an array,
list, or a string of size.
6
static <T> T checkNotNull(T reference)
Ensures that an object reference passed as a parameter to
the calling method is not null.
7
static <T> T checkNotNull(T reference, Object
errorMessage)
Ensures that an object reference passed as a parameter to
the calling method is not null.
8
static <T> T checkNotNull(T reference, String
errorMessageTemplate, Object… errorMessageArgs)
Ensures that an object reference passed as a parameter to
the calling method is not null.
9
static int checkPositionIndex(int index, int size)
Ensures that index specifies a valid position in an array,
list or a string of size.
10
static int checkPositionIndex(int index, int size,
String desc)
Ensures that index specifies a valid position in an array,
list or a string of size.
11
static void checkPositionIndexes(int start, int end, int
size)
Ensures that start and end specify a valid positions in an
array, list or a string of size, and are in order.
12
static void checkState(boolean expression)
Ensures the truth of an expression involving the state of
the calling instance, but not involving any parameters to
the calling method.
13
static void checkState(boolean expression, Object
errorMessage)
Ensures the truth of an expression involving the state of
the calling instance, but not involving any parameters to
the calling method.
14
static void checkState(boolean expression, String
errorMessageTemplate, Object… errorMessageArgs)
Ensures the truth of an expression involving the state of
the calling instance, but not involving any parameters to
the calling method.

Methods Inherited

This class inherits methods from the following class −
  • java.lang.Object

Example of Preconditions Class

Create the following java program using any editor of your choice
in say C:/> Guava.

GuavaTester.java

import com.google.common.base.Preconditions;

public class GuavaTester {

public static void main(String args[]) {
GuavaTester guavaTester = new GuavaTester();

try {
System.out.println(guavaTester.sqrt(-3.0));
} catch(IllegalArgumentException e) {
System.out.println(e.getMessage());
}

try {
System.out.println(guavaTester.sum(null,3));
} catch(NullPointerException e) {
System.out.println(e.getMessage());
}

try {
System.out.println(guavaTester.getValue(6));
} catch(IndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}

public double sqrt(double input) throws IllegalArgumentException {
Preconditions.checkArgument(input > 0.0,
"Illegal Argument passed: Negative value %s.", input);
return Math.sqrt(input);
}

public int sum(Integer a, Integer b) {
a = Preconditions.checkNotNull(a, "Illegal Argument passed: First parameter is Null.");
b = Preconditions.checkNotNull(b, "Illegal Argument passed: Second parameter is Null.");

return a+b;
}

public int getValue(int input) {
int[] data = {1,2,3,4,5};
Preconditions.checkElementIndex(input,data.length, "Illegal Argument passed: Invalid index.");
return 0;
}
}

Verify the Result

Compile the class using javac compiler as follows −
C:Guava>javac GuavaTester.java
Now run the GuavaTester to see the result.
C:Guava>java GuavaTester
See the result.
Illegal Argument passed: Negative value -3.0.
Illegal Argument passed: First parameter is Null.
Illegal Argument passed: Invalid index. (6) must be less than size (5)

Guava – Ordering Class

Ordering can be seen as an enriched comparator with enhanced
chaining functionality, multiple utility methods, multi-type
sorting capability, etc.

Class Declaration

Following is the declaration for
com.google.common.collect.Ordering<T> class −
@GwtCompatible
public abstract class Ordering<T>
extends Object
implements Comparator<T>

Class Methods

SR.NOMETHOD & DESCRIPTION
1
static Ordering<Object> allEqual()
Returns an ordering which treats all values as equal,
indicating “no ordering.” Passing this ordering to any
stable sort algorithm results in no change to the order of
elements.
2
static Ordering<Object> arbitrary()
Returns an arbitrary ordering over all objects, for which
compare(a, b) == 0 implies a == b (identity equality).
3
int binarySearch(List<? extends T> sortedList, T
key)
Searches sortedList for key using the binary search
algorithm.
4
abstract int compare(T left, T right)
Compares its two arguments for order.
5
<U extends T> Ordering<U>
compound(Comparator<? super U>
secondaryComparator)
Returns an ordering which first uses the ordering this, but
which in the event of a “tie”, then delegates to
secondaryComparator.
6
static <T> Ordering<T>
compound(Iterable<? extends Comparator<? super
T>> comparators)
Returns an ordering which tries each given comparator in
order until a non-zero result is found, returning that
result, and returning zero only if all comparators return
zero.
7
static <T> Ordering<T>
explicit(List<T> valuesInOrder)
Returns an ordering that compares objects according to the
order in which they appear in the given list.
8
static <T> Ordering<T> explicit(T
leastValue, T… remainingValuesInOrder)
Returns an ordering that compares objects according to the
order in which they are given to this method.
9
static <T> Ordering<T>
from(Comparator<T> comparator)
Returns an ordering based on an existing comparator
instance.
10
<E extends T> List<E>
greatestOf(Iterable<E> iterable, int k)
Returns the k greatest elements of the given iterable
according to this ordering, in order from greatest to
least.
11
<E extends T> List<E>
greatestOf(Iterator<E> iterator, int k)
Returns the k greatest elements from the given iterator
according to this ordering, in order from greatest to
least.
12
<E extends T> ImmutableList<E>
immutableSortedCopy(Iterable<E> elements)
Returns an immutable list containing elements sorted by
this ordering.
13
boolean isOrdered(Iterable<? extends T>
iterable)
Returns true if each element in iterable after the first is
greater than or equal to the element that preceded it,
according to this ordering.
14
boolean isStrictlyOrdered(Iterable<? extends T>
iterable)
Returns true if each element in iterable after the first is
strictly greater than the element that preceded it,
according to this ordering
15
<E extends T> List<E>
leastOf(Iterable<E> iterable, int k)
Returns the k least elements of the given iterable
according to this ordering, in order from least to
greatest.
16
<E extends T> List<E>
leastOf(Iterator<E> elements, int k)
Returns the k least elements from the given iterator
according to this ordering, in order from least to
greatest.
17
<S extends T> Ordering<Iterable<S>>
lexicographical()
Returns a new ordering which sorts iterables by comparing
corresponding elements pairwise until a nonzero result is
found; imposes “dictionary order”.
18
<E extends T> E max(E a, E b)
Returns the greater of the two values according to this
ordering.
19
<E extends T> E max(E a, E b, E c, E… rest)
Returns the greatest of the specified values according to
this ordering.
20
<E extends T> E max(Iterable<E>
iterable)
Returns the greatest of the specified values according to
this ordering.
21
<E extends T> E max(Iterator<E>
iterator)
Returns the greatest of the specified values according to
this ordering.
22
<E extends T> E min(E a, E b)
Returns the lesser of the two values according to this
ordering.
23
<E extends T> E min(E a, E b, E c, E… rest)
Returns the least of the specified values according to this
ordering.
24
<E extends T> E min(Iterable<E>
iterable)
Returns the least of the specified values according to this
ordering.
25
<E extends T> E min(Iterator<E>
iterator)
Returns the least of the specified values according to this
ordering.
26
static <C extends Comparable> Ordering<C>
natural()
Returns a serializable ordering that uses the natural order
of the values.
27
<S extends T> Ordering<S> nullsFirst()
Returns an ordering that treats null as less than all other
values and uses this to compare non-null values.
28
<S extends T> Ordering<S> nullsLast()
Returns an ordering that treats null as greater than all
other values and uses this ordering to compare non-null
values.
29
<F> Ordering<F> onResultOf(Function<F,?
extends T> function)
Returns a new ordering on F which orders elements by first
applying a function to them, then comparing those results
using this.
30
<S extends T> Ordering<S> reverse()
Returns the reverse of this ordering; the Ordering
equivalent to Collections.reverseOrder(Comparator).
31
<E extends T> List<E>
sortedCopy(Iterable<E> elements)
Returns a mutable list containing elements sorted by this
ordering; use this only when the resulting list may need
further modification, or may contain null.
32
static Ordering<Object> usingToString()
Returns an ordering that compares objects by the natural
ordering of their string representations as returned by
toString().

Methods Inherited

This class inherits methods from the following class −
  • java.lang.Object

Example of Ordering Class

Create the following java program using any editor of your choice
in say C:/> Guava.

GuavaTester.java

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.google.common.collect.Ordering;

public class GuavaTester {
public static void main(String args[]) {
List<Integer> numbers = new ArrayList<Integer>();

numbers.add(new Integer(5));
numbers.add(new Integer(2));
numbers.add(new Integer(15));
numbers.add(new Integer(51));
numbers.add(new Integer(53));
numbers.add(new Integer(35));
numbers.add(new Integer(45));
numbers.add(new Integer(32));
numbers.add(new Integer(43));
numbers.add(new Integer(16));

Ordering ordering = Ordering.natural();
System.out.println("Input List: ");
System.out.println(numbers);

Collections.sort(numbers,ordering );
System.out.println("Sorted List: ");
System.out.println(numbers);

System.out.println("======================");
System.out.println("List is sorted: " + ordering.isOrdered(numbers));
System.out.println("Minimum: " + ordering.min(numbers));
System.out.println("Maximum: " + ordering.max(numbers));

Collections.sort(numbers,ordering.reverse());
System.out.println("Reverse: " + numbers);

numbers.add(null);
System.out.println("Null added to Sorted List: ");
System.out.println(numbers);

Collections.sort(numbers,ordering.nullsFirst());
System.out.println("Null first Sorted List: ");
System.out.println(numbers);
System.out.println("======================");

List<String> names = new ArrayList<String>();

names.add("Ram");
names.add("Shyam");
names.add("Mohan");
names.add("Sohan");
names.add("Ramesh");
names.add("Suresh");
names.add("Naresh");
names.add("Mahesh");
names.add(null);
names.add("Vikas");
names.add("Deepak");

System.out.println("Another List: ");
System.out.println(names);

Collections.sort(names,ordering.nullsFirst().reverse());
System.out.println("Null first then reverse sorted list: ");
System.out.println(names);
}
}

Verify the Result

Compile the class using javac compiler as follows −
C:Guava>javac GuavaTester.java
Now run the GuavaTester to see the result.
C:Guava>java GuavaTester
See the result.
Input List: 
[5, 2, 15, 51, 53, 35, 45, 32, 43, 16]
Sorted List:
[2, 5, 15, 16, 32, 35, 43, 45, 51, 53]
======================
List is sorted: true
Minimum: 2
Maximum: 53
Reverse: [53, 51, 45, 43, 35, 32, 16, 15, 5, 2]
Null added to Sorted List:
[53, 51, 45, 43, 35, 32, 16, 15, 5, 2, null]
Null first Sorted List:
[null, 2, 5, 15, 16, 32, 35, 43, 45, 51, 53]
======================
Another List:
[Ram, Shyam, Mohan, Sohan, Ramesh, Suresh, Naresh, Mahesh, null, Vikas, Deepak]
Null first then reverse sorted list:
[Vikas, Suresh, Sohan, Shyam, Ramesh, Ram, Naresh, Mohan, Mahesh, Deepak, null]

Guava – Objects Class

Objects class provides helper functions applicable to all objects
such as equals, hashCode, etc.

Class Declaration

Following is the declaration for
com.google.common.base.Objects class −
@GwtCompatible
public final class Objects
extends Object

Class Methods

SR.NOMETHOD & DESCRIPTION
1
static boolean equal(Object a, Object b)
Determines whether two possibly-null objects are equal.
2
static <T> T firstNonNull(T first, T second)
Deprecated. Use MoreObjects.firstNonNull(T, T) instead.
This method is scheduled for removal in June 2016.
3
static int hashCode(Object… objects)
Generates a hash code for multiple values.
4
static Objects.ToStringHelper
toStringHelper(Class<?> clazz)
Deprecated. Use MoreObjects.toStringHelper(Class) instead.
This method is scheduled for removal in June 2016
5
static Objects.ToStringHelper toStringHelper(Object
self)
Deprecated. Use MoreObjects.toStringHelper(Object) instead.
This method is scheduled for removal in June 2016.
6
static Objects.ToStringHelper toStringHelper(String
className)
Deprecated. Use MoreObjects.toStringHelper(String) instead.
This method is scheduled for removal in June 2016.

Methods Inherited

This class inherits methods from the following class −
  • java.lang.Object

Example of Objects Class

Create the following java program using any editor of your choice
in say C:/> Guava.

GuavaTester.java

import com.google.common.base.Objects;

public class GuavaTester {
public static void main(String args[]) {
Student s1 = new Student("Mahesh", "Parashar", 1, "VI");
Student s2 = new Student("Suresh", null, 3, null);

System.out.println(s1.equals(s2));
System.out.println(s1.hashCode());
System.out.println(
Objects.toStringHelper(s1)
.add("Name",s1.getFirstName()+" " + s1.getLastName())
.add("Class", s1.getClassName())
.add("Roll No", s1.getRollNo())
.toString());
}
}

class Student {
private String firstName;
private String lastName;
private int rollNo;
private String className;

public Student(String firstName, String lastName, int rollNo, String className) {
this.firstName = firstName;
this.lastName = lastName;
this.rollNo = rollNo;
this.className = className;
}

@Override
public boolean equals(Object object) {
if(!(object instanceof Student) || object == null) {
return false;
}
Student student = (Student)object;
// no need to handle null here
// Objects.equal("test", "test") == true
// Objects.equal("test", null) == false
// Objects.equal(null, "test") == false
// Objects.equal(null, null) == true
return Objects.equal(firstName, student.firstName) // first name can be null
&& Objects.equal(lastName, student.lastName) // last name can be null
&& Objects.equal(rollNo, student.rollNo)
&& Objects.equal(className, student.className); // class name can be null
}

@Override
public int hashCode() {
//no need to compute hashCode by self
return Objects.hashCode(className,rollNo);
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public int getRollNo() {
return rollNo;
}

public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}

public String getClassName() {
return className;
}

public void setClassName(String className) {
this.className = className;
}
}

Verify the Result

Compile the class using javac compiler as follows −
C:Guava>javac GuavaTester.java
Now run the GuavaTester to see the result.
C:Guava>java GuavaTester
See the result.
false
85871
Student{Name=Mahesh Parashar, Class=VI, Roll No=1}

Guava – Range Class

Range represents an interval or a sequence. It is used to get a
set of numbers/ strings lying in a particular range.

Class Declaration

Following is the declaration for
com.google.common.collect.Range<C> class −
@GwtCompatible
public final class Range<C extends Comparable>
extends Object
implements Predicate<C>, Serializable

Methods

SR.NOMETHOD & DESCRIPTION
1
static <C extends Comparable<?>>
Range<C> all()
Returns a range that contains every value of type C.
2
boolean apply(C input)Deprecated.
Provided only to satisfy the Predicate interface; use
contains(C) instead.
3
static <C extends Comparable<?>>
Range<C> atLeast(C endpoint)
Returns a range that contains all values greater than or
equal to endpoint.
4
static <C extends Comparable<?>>
Range<C> atMost(C endpoint)
Returns a range that contains all values less than or equal
to endpoint.
5
Range<C> canonical(DiscreteDomain<C>
domain)
Returns the canonical form of this range in the given
domain.
6
static <C extends Comparable<?>>
Range<C> closed(C lower, C upper)
Returns a range that contains all values greater than or
equal to lower and less than or equal to upper.
7
static <C extends Comparable<?>>
Range<C> closedOpen(C lower, C upper)
Returns a range that contains all values greater than or
equal to lower and strictly less than upper.
8
boolean contains(C value)
Returns true if value is within the bounds of this range.
9
boolean containsAll(Iterable<? extends C>
values)
Returns true if every element in values is contained in
this range.
10
static <C extends Comparable<?>>
Range<C> downTo(C endpoint, BoundType boundType)
Returns a range from the given endpoint, which may be
either inclusive (closed) or exclusive (open), with no
upper bound.
11
static <C extends Comparable<?>>
Range<C> encloseAll(Iterable<C> values)
Returns the minimal range that contains all of the given
values.
12
boolean encloses(Range<C> other)
Returns true if the bounds of other do not extend outside
the bounds of this range.
13
boolean equals(Object object)
Returns true if object is a range having the same endpoints
and bound types as this range.
14
static <C extends Comparable<?>>
Range<C> greaterThan(C endpoint)
Returns a range that contains all values strictly greater
than endpoint.
15
int hashCode()
Returns a hash code for this range.
16
boolean hasLowerBound()
Returns true if this range has a lower endpoint.
17
boolean hasUpperBound()
Returns true if this range has an upper endpoint.
18
Range<C> intersection(Range<C>
connectedRange)
Returns the maximal range enclosed by both this range and
connectedRange, if such a range exists.
19
boolean isConnected(Range<C> other)
Returns true if there exists a (possibly empty) range which
is enclosed by both this range and other.
20
boolean isEmpty()
Returns true if this range is of the form [v..v) or (v..v].
21
static <C extends Comparable<?>>
Range<C> lessThan(C endpoint)
Returns a range that contains all values strictly less than
endpoint.
22
BoundType lowerBoundType()
Returns the type of this range’s lower bound:
BoundType.CLOSED if the range includes its lower endpoint,
BoundType.OPEN if it does not.
23
C lowerEndpoint()
Returns the lower endpoint of this range.
24
static <C extends Comparable<?>>
Range<C> open(C lower, C upper)
Returns a range that contains all values strictly greater
than lower and strictly less than upper.
25
static <C extends Comparable<?>>
Range<C> openClosed(C lower, C upper)
Returns a range that contains all values strictly greater
than lower and less than or equal to upper.
26
static <C extends Comparable<?>>
Range<C> range(C lower, BoundType lowerType, C upper,
BoundType upperType)
Returns a range that contains any value from lower to
upper, where each endpoint may be either inclusive (closed)
or exclusive (open).
27
static <C extends Comparable<?>>
Range<C> singleton(C value)
Returns a range that contains only the given value.
28
Range<C> span(Range<C> other)
Returns the minimal range that encloses both this range and
other.
29
String toString()
Returns a string representation of this range, such as
“[3..5)” (other examples are listed in the class
documentation).
30
BoundType upperBoundType()
Returns the type of this range’s upper bound:
BoundType.CLOSED if the range includes its upper endpoint,
BoundType.OPEN if it does not.
31
C upperEndpoint()
Returns the upper endpoint of this range.
32
static <C extends Comparable<?>>
Range<C> upTo(C endpoint, BoundType boundType)
Returns a range with no lower bound up to the given
endpoint, which may be either inclusive (closed) or
exclusive (open).

Methods Inherited

This class inherits methods from the following class −
  • java.lang.Object

Example of Range Class

Create the following java program using any editor of your choice
in say C:/> Guava.

GuavaTester.java

import com.google.common.collect.ContiguousSet;
import com.google.common.collect.DiscreteDomain;
import com.google.common.collect.Range;
import com.google.common.primitives.Ints;

public class GuavaTester {

public static void main(String args[]) {
GuavaTester tester = new GuavaTester();
tester.testRange();
}

private void testRange() {

//create a range [a,b] = { x | a <= x <= b}
Range<Integer> range1 = Range.closed(0, 9);
System.out.print("[0,9] : ");
printRange(range1);

System.out.println("5 is present: " + range1.contains(5));
System.out.println("(1,2,3) is present: " + range1.containsAll(Ints.asList(1, 2, 3)));
System.out.println("Lower Bound: " + range1.lowerEndpoint());
System.out.println("Upper Bound: " + range1.upperEndpoint());

//create a range (a,b) = { x | a < x < b}
Range<Integer> range2 = Range.open(0, 9);
System.out.print("(0,9) : ");
printRange(range2);

//create a range (a,b] = { x | a < x <= b}
Range<Integer> range3 = Range.openClosed(0, 9);
System.out.print("(0,9] : ");
printRange(range3);

//create a range [a,b) = { x | a <= x < b}
Range<Integer> range4 = Range.closedOpen(0, 9);
System.out.print("[0,9) : ");
printRange(range4);

//create an open ended range (9, infinity
Range<Integer> range5 = Range.greaterThan(9);
System.out.println("(9,infinity) : ");
System.out.println("Lower Bound: " + range5.lowerEndpoint());
System.out.println("Upper Bound present: " + range5.hasUpperBound());

Range<Integer> range6 = Range.closed(3, 5);
printRange(range6);

//check a subrange [3,5] in [0,9]
System.out.println("[0,9] encloses [3,5]:" + range1.encloses(range6));

Range<Integer> range7 = Range.closed(9, 20);
printRange(range7);

//check ranges to be connected
System.out.println("[0,9] is connected [9,20]:" + range1.isConnected(range7));
Range<Integer> range8 = Range.closed(5, 15);

//intersection
printRange(range1.intersection(range8));

//span
printRange(range1.span(range8));
}

private void printRange(Range<Integer> range) {

System.out.print("[ ");

for(int grade : ContiguousSet.create(range, DiscreteDomain.integers())) {
System.out.print(grade +" ");
}
System.out.println("]");
}
}

Verify the Result

Compile the class using javac compiler as follows −
C:Guava>javac GuavaTester.java
Now run the GuavaTester to see the result.
C:Guava>java GuavaTester
See the result.
[0,9] : [ 0 1 2 3 4 5 6 7 8 9 ]
5 is present: true
(1,2,3) is present: true
Lower Bound: 0
Upper Bound: 9
(0,9) : [ 1 2 3 4 5 6 7 8 ]
(0,9] : [ 1 2 3 4 5 6 7 8 9 ]
[0,9) : [ 0 1 2 3 4 5 6 7 8 ]
(9,infinity) :
Lower Bound: 9
Upper Bound present: false
[ 3 4 5 ]
[0,9] encloses [3,5]:true
[ 9 10 11 12 13 14 15 16 17 18 19 20 ]
[0,9] is connected [9,20]:true
[ 5 6 7 8 9 ]
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ]

Guava – Throwables Class

Throwables class provides utility methods related to Throwable
interface.

Class Declaration

Following is the declaration for
com.google.common.base.Throwables class −
public final class Throwables
extends Object

Class Methods

SR.NOMETHOD & DESCRIPTION
1
static List<Throwable> getCausalChain(Throwable
throwable)
Gets a Throwable cause chain as a list.
2
static Throwable getRootCause(Throwable throwable)
Returns the innermost cause of throwable.
3
static String getStackTraceAsString(Throwable
throwable)
Returns a string containing the result of toString(),
followed by the full, recursive stack trace of throwable.
4
static RuntimeException propagate(Throwable
throwable)
Propagates throwable as-is if it is an instance of
RuntimeException or Error, or else as a last resort, wraps
it in a RuntimeException then propagates.
5
static <X extends Throwable> void
propagateIfInstanceOf(Throwable throwable, Class<X>
declaredType)
Propagates throwable exactly as-is, if and only if it is an
instance of declaredType.
6
static void propagateIfPossible(Throwable throwable)
Propagates throwable exactly as-is, if and only if it is an
instance of RuntimeException or Error.
7
static <X extends Throwable> void
propagateIfPossible(Throwable throwable, Class<X>
declaredType)
Propagates throwable exactly as-is, if and only if it is an
instance of RuntimeException, Error, or declaredType.
8
static <X1 extends Throwable,X2 extends
Throwable>void propagateIfPossible(Throwable throwable,
Class<X1> declaredType1, Class<X2>
declaredType2)
Propagates throwable exactly as-is, if and only if it is an
instance of RuntimeException, Error, declaredType1, or
declaredType2.

Methods Inherited

This class inherits methods from the following class −
  • java.lang.Object

Example of Throwables Class

Create the following java program using any editor of your choice
in say C:/> Guava.

GuavaTester.java

import java.io.IOException;

import com.google.common.base.Objects;
import com.google.common.base.Throwables;

public class GuavaTester {
public static void main(String args[]) {

GuavaTester tester = new GuavaTester();

try {
tester.showcaseThrowables();

} catch (InvalidInputException e) {
//get the root cause
System.out.println(Throwables.getRootCause(e));

} catch (Exception e) {
//get the stack trace in string format
System.out.println(Throwables.getStackTraceAsString(e));
}

try {
tester.showcaseThrowables1();

} catch (Exception e) {
System.out.println(Throwables.getStackTraceAsString(e));
}
}

public void showcaseThrowables() throws InvalidInputException {
try {
sqrt(-3.0);
} catch (Throwable e) {
//check the type of exception and throw it
Throwables.propagateIfInstanceOf(e, InvalidInputException.class);
Throwables.propagate(e);
}
}

public void showcaseThrowables1() {
try {
int[] data = {1,2,3};
getValue(data, 4);
} catch (Throwable e) {
Throwables.propagateIfInstanceOf(e, IndexOutOfBoundsException.class);
Throwables.propagate(e);
}
}

public double sqrt(double input) throws InvalidInputException {
if(input < 0) throw new InvalidInputException();
return Math.sqrt(input);
}

public double getValue(int[] list, int index) throws IndexOutOfBoundsException {
return list[index];
}

public void dummyIO() throws IOException {
throw new IOException();
}
}

class InvalidInputException extends Exception {
}

Verify the Result

Compile the class using javac compiler as follows −
C:Guava>javac GuavaTester.java
Now run the GuavaTester to see the result.
C:Guava>java GuavaTester
See the result.
InvalidInputException
java.lang.ArrayIndexOutOfBoundsException: 4
at GuavaTester.getValue(GuavaTester.java:52)
at GuavaTester.showcaseThrowables1(GuavaTester.java:38)
at GuavaTester.main(GuavaTester.java:19)

Guava – Collections Utilities

Guava introduces many advanced collections based on developers’
experience in application development works. Given below is a
list of useful collections −
SR.NOCOLLECTION NAME & DESCRIPTION
1
An extension to Set interface to allow duplicate elements.
2
An extension to Map interface so that its keys can be
mapped to multiple values at a time.
3
An extension to Map interface to support inverse
operations.
4
Table represents a special map where two keys can be
specified in combined fashion to refer to a single value.

Guava – Caching Utilities

Guava provides a very powerful memory based caching mechanism by
an interface LoadingCache<K,V>. Values are automatically
loaded in the cache and it provides many utility methods useful
for caching needs.

Interface Declaration

Following is the declaration for
com.google.common.cache.LoadingCache<K,V> interface
@Beta
@GwtCompatible
public interface LoadingCache<K,V>
extends Cache<K,V>, Function<K,V>

Interface Methods

SR.NOMETHOD & DESCRIPTION
1
V apply(K key)
Deprecated. Provided to satisfy the Function interface; use
get(K) or getUnchecked(K) instead.
2
ConcurrentMap<K,V> asMap()
Returns a view of the entries stored in this cache as a
thread-safe map.
3
V get(K key)
Returns the value associated with key in this cache, first
loading that value if necessary.
4
ImmutableMap<K,V> getAll(Iterable<? extends
K> keys)
Returns a map of the values associated with keys, creating
or retrieving those values if necessary.
5
V getUnchecked(K key)
Returns the value associated with key in this cache, first
loading that value if necessary.
6
void refresh(K key)
Loads a new value for key, possibly asynchronously.

Example of LoadingCache

Create the following java program using any editor of your choice
in say C:/> Guava.

GuavaTester.java

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import com.google.common.base.MoreObjects;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

public class GuavaTester {
public static void main(String args[]) {

//create a cache for employees based on their employee id
LoadingCache<String, Employee> employeeCache =
CacheBuilder.newBuilder()
.maximumSize(100) // maximum 100 records can be cached
.expireAfterAccess(30, TimeUnit.MINUTES) // cache will expire after 30 minutes of access
.build(new CacheLoader<String, Employee>() { // build the cacheloader

@Override
public Employee load(String empId) throws Exception {
//make the expensive call
return getFromDatabase(empId);
}
});

try {
//on first invocation, cache will be populated with corresponding
//employee record
System.out.println("Invocation #1");
System.out.println(employeeCache.get("100"));
System.out.println(employeeCache.get("103"));
System.out.println(employeeCache.get("110"));

//second invocation, data will be returned from cache
System.out.println("Invocation #2");
System.out.println(employeeCache.get("100"));
System.out.println(employeeCache.get("103"));
System.out.println(employeeCache.get("110"));

} catch (ExecutionException e) {
e.printStackTrace();
}
}

private static Employee getFromDatabase(String empId) {

Employee e1 = new Employee("Mahesh", "Finance", "100");
Employee e2 = new Employee("Rohan", "IT", "103");
Employee e3 = new Employee("Sohan", "Admin", "110");

Map<String, Employee> database = new HashMap<String, Employee>();

database.put("100", e1);
database.put("103", e2);
database.put("110", e3);

System.out.println("Database hit for" + empId);

return database.get(empId);
}
}

class Employee {
String name;
String dept;
String emplD;

public Employee(String name, String dept, String empID) {
this.name = name;
this.dept = dept;
this.emplD = empID;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getDept() {
return dept;
}

public void setDept(String dept) {
this.dept = dept;
}

public String getEmplD() {
return emplD;
}

public void setEmplD(String emplD) {
this.emplD = emplD;
}

@Override
public String toString() {
return MoreObjects.toStringHelper(Employee.class)
.add("Name", name)
.add("Department", dept)
.add("Emp Id", emplD).toString();
}
}

Verify the Result

Compile the class using javac compiler as follows −
C:Guava>javac GuavaTester.java
Now run the GuavaTester to see the result.
C:Guava>java GuavaTester
See the result.
Invocation #1
Database hit for100
Employee{Name=Mahesh, Department=Finance, Emp Id=100}
Database hit for103
Employee{Name=Rohan, Department=IT, Emp Id=103}
Database hit for110
Employee{Name=Sohan, Department=Admin, Emp Id=110}
Invocation #2
Employee{Name=Mahesh, Department=Finance, Emp Id=100}
Employee{Name=Rohan, Department=IT, Emp Id=103}
Employee{Name=Sohan, Department=Admin, Emp Id=110}

Guava – String Utilities

Guava introduces many advanced string utilities based on
developers’ experience in application development works.
Following is the list of useful string based utilities −
SR.NOUTILITY NAME & DESCRIPTION
1
Utility to join objects, string etc.
2
Utility to split string.
3
Utility for character operations.
4
Utility for changing string formats.

Guava – Primitive Utilities

As primitive types of Java cannot be used to pass in generics or
in collections as input, Guava provided a lot of Wrapper
Utilities classes to handle primitive types as Objects. Following
is the list of useful primitive processing utilities −
SR.NOUTILITY NAME & DESCRIPTION
1
Utility for primitive byte.
2
Utility for primitive short.
3
Utility for primitive int.
4
Utility for primitive long.
5
Utility for primitive float.
6
Utility for primitive double.
7
Utility for primitive char.
8
Utility for primitive boolean.

Guava – Math Utilities

Guava provides Mathematics related Utilities classes to handle
int, long and BigInteger. Following is the list of useful
utilities −
SR.NOUTILITY NAME & DESCRIPTION
1
Math utility for int.
2
Math utility for long.
3
Math utility for BigInteger.

Comments

Popular posts from this blog

Mad Scientist Profits Review – A Legit Method To Make Money Online

Targeting Academy 2.0 (2019) Review

Holiday SocialPacks Review – Cash In By Helping People Fight Against Corporations