Guava’s ImmutableList Class in Java

In this post, we will talk about Guava’s ImmutableList class in Java which provides several static utility methods for creating Immutable Lists in Java and to operate on them.


 

1. ImmutableList.of()

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

 
static ImmutableList of()
static ImmutableList of(E element)
static ImmutableList of(E e1, E e2)
....
....
static ImmutableList of(E e1, E e2, E e3, . . . E e10, E e11)
static ImmutableList of(E e1, E e2, E e3, . . . E e11, E e12, E... others)

 

Download   Run Code

 

2. Builder

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

 

Download   Run Code

 

3. ImmutableList.copyOf()

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

 

Download   Run Code

 

4. ImmutableList.reverse()

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

 

Download   Run Code

 

5. ImmutableList.subList()

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   Run Code

 

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

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

 

Download   Run Code

 

ImmutableList.indexOf() method works in similar way but returns the index of last occurrence.

 

7. ImmutableList.contains()

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

 

Download   Run Code

 

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of