This post will talk about Guava’s ImmutableList class in Java, which provides several static utility methods for creating Immutable lists in Java and operating on them.

1. Using ImmutableList.of() method

Guava’s ImmutableList.of() returns an immutable list having the given elements. It has 7 overloaded versions, the last one with var-args to handle any number of elements.

static <E> ImmutableList<E> of()
static <E> ImmutableList<E> of(E element)
static <E> ImmutableList<E> of(E e1, E e2)
static <E> ImmutableList<E> of(E e1, E e2, E e3)
static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4)
static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5)
static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E… others)

Here’s Java program to demonstrate Guava’s ImmutableList.of() method:

Download Code

2. Using Builder

Guava also provides a builder for creating immutable list instances, as shown below:

Download Code

3. Using ImmutableList.copyOf() method

Guava’s ImmutableList.copyOf() method returns an immutable list containing elements of the specified collection, a non-primitive array, or an iterator.

Download Code

4. Using ImmutableList.reverse() method

Guava’s ImmutableList.reverse() returns a reversed view of the specified immutable list.

Download Code

5. Using ImmutableList.subList() method

Guava’s ImmutableList.subList() method returns an immutable list of the elements between the specified indices. The starting index is inclusive, and the ending index is exclusive.

Download Code

6. Using ImmutableList indexOf() and lastIndexOf() method

Guava’s ImmutableList.indexOf() method returns the index of the first occurrence of the specified element in the immutable list and returns -1 if the element is not present in the list.

Download Code

 

ImmutableList.indexOf() method works similarly but returns the index of the last occurrence.

7. Using ImmutableList.contains() method

Guava’s ImmutableList.contains() method determines if the specified element is present in the immutable list or not.

Download Code

That’s all about Guava’s ImmutableList class in Java.