Guava Collections Tutorial

Perhaps at the foundation of Guava are its utilities for working with Java collections. After all, Guava started at as The Google Collections Library. By far, more classes live in the com.google.common.collect package than any other proving its significance to Guava.

Lists

The Lists class, as its name implies, provides utilities for working with Java List instances. Namely, it provides utilities for creating lists, creating lists with enumerated elements, and for manipulating lists.

Creating List Instances

One of the most commonly used methods in the Lists class are the newArrayList() and the newLinkedList() methods. Both, and their variations, making creating lists very simple. Let’s see these methods in action.


// Creates a new array list
List names = Lists.newArrayList();

// Creates a new linked list
List ages = Lists.newLinkedList();

// Creates a new array list with the provided data
List salaries = Lists.newArrayList(50000, 75000, 100000, 125000);

// Creates a new linked list with the provided data
List animals = Lists.newLinkedList(cat, dog, cow, pig);

// Creates a new array list with an initial capacity
List movies = Lists.newArrayListWithCapacity(50);

// Creates a new linked list with an initial capacity
List books = Lists.newLinkedListWithCapacity(100);

As you can see, the Guava way of creating List instances if straight-forward and concise. It has the added benefit of being able to enumerate the initial elements in the list on the same line, something you cannot due with the Java language collections framework alone.

Reversing a List

The Guava Lists class provides an easy way to reverse a list in a single line of code.



// Create a list of ages in ascending order.
List ages = Lists.newArrayList(10, 20, 30, 40, 50);

// Reverse the list so the ages are in descending order.
ages = Lists.reverse(ages);

// Now the list contents are 50, 40, 30, 20, 10.

Partitioning a List

Guava also provides a mechanism to partition a List into multiple List objects. This can be handing for divvying out data to a Map-Reduce algorithm or to break apart a sorted list based on ranges.



// Create a list of ages.
List> partionedLists = Lists.partition(ages, 2);

// The first list now contains elements 10, 20, 30 and the second list contains elements 40 and 50


The partion() method simply takes a list as the first argument and the number of partitions as the second element. It returns a list containing the specified number of list partitions.