This article will discuss Guava Lists class, which provides several static utility methods pertaining to List instances in Java.

The Lists class is one of the most commonly used class in Guava, which offers the following static utility methods:

1. Using Lists.asList() method

We can’t insert a new element to an array as the array size is fixed in Java. One solution to this problem is to allocate a new array of +1 the size of the original array, and copy all elements from the original array to the new array. This works, but it is highly inefficient. Guava provides an efficient solution to this problem: The Lists.asList() method returns an unmodifiable list backed by the original array, which also contains the specified element. This is useful for adding an element to an array without creating a new array.

Download Code

2. Using Lists.charactersOf() method

Guava’s Lists.charactersOf() method returns a view of the specified string as an immutable list of Character values. No actual copying happens here as this method just returns a view and throws an UnsupportedOperationException if we try to modify the list. This method is often used to iterate over the characters of a string using a for-each loop or an iterator.

Download Code

3. Using Lists.newArrayList() method

Guava library provides the Lists.newArrayList() utility method that returns a mutable ArrayList instance containing elements from the specified iterable. This is a convenient way to create a list from an array, a collection, or any other iterable. To get an immutable list, Guava provides the ImmutableList.copyOf() method.

Download Code

4. Using Lists.reverse() method

Guava Lists class also provides the reverse() utility method that returns a reversed view of the specified list. The returned list is backed by the original list, so any changes in the returned list are reflected in the original list and vice-versa.

Download Code

5. Using Lists.transform() method

Guava’s Lists.transform() method returns a list after applying a specified method to each element of the original list. The transformation happens in such a way that any changes to the original list will be reflected in the returned list, but no new elements can be added to the returned list.

Download Code

6. Using Lists.partition() method

Guava’s Lists.partition() method divides a list into sublists of the same size, which are just views of the original list. The final list may be smaller. This is useful for splitting a large list into smaller sublists.

Download Code

That’s all about Lists class by Guava in Java.