Guava’s Lists Class in Java

In this article, we will talk about Guava Lists class which provides several static utility methods pertaining to List instances.

 
Lists class is one of the most commonly used class which offers below static utility methods:

 

1. Lists.asList()

Suppose we have an array, and we want to insert an element to it, we can’t do it as the array size is fixed. One solution to this problem is to allocate an 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 efficent solution to this problem – Guava’s Lists.asList() method returns an unmodifiable list backed by the original array which also contains the specified element.

 

Download   Run Code

Output:

[10, 30, 40, 50]
[10, 20, 30, 40, 50]
[30, 40, 50]

 

2. Lists.charactersOf()

Sometimes we need the individual characters of a String. Guava’s Lists.charactersOf() method returns a view of the specified string as an immutable list of Character values. Please note that no actual copying happens here as this method just returns a view and throws an UnsupportedOperationException if we try to modify the list.

 

Download   Run Code

Output:

[G, u, a, v, a, ‘, s, , L, i, s, t, s, , C, l, a, s, s]

 

This method is often used to iterate over characters of a String using a for-each loop or an iterator.

 

Download   Run Code

Output:

Techie Delight
Techie Delight

 

 

3. Lists.newArrayList()

Guava library provides Lists.newArrayList() utility method that returns a mutable ArrayList instance containing elements from a non-primitive array, an iterable or an iterator. To get an immutable list, we can use ImmutableList.copyOf() method.

 

Download   Run Code

Output:

[]
[1, 2, 3]
[1, 2, 3, 4, 5]

 

4. Lists.reverse()

Guava’s Lists.reverse() returns a reversed view of the specified list. Any changes in the returned list are reflected in the original list, and vice-versa.

 

Download   Run Code

Output:

[5, 4, 3, 2, 1]

 

5. Lists.transform()

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

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 

6. Lists.partition()

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

 

Download   Run Code

Output:

[1, 2]
[3, 4]
[5]

 
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