Create, Partition and Reverse Array List Using Guava Lists


Guava Lists is part of the Guava core java library. It is used to perform many frequently used operations on an array lists like creation, partition, reversal, and many more.

Java Guava lib is collection of very safe and handy libs for working with collection types (such as list, multimap, bimap, and multiset), immutable collections, a graph library, and it also provides many utilities for concurrency, I/O, Math, XML, hashing, caching, primitives, strings, and more.

This provides many functionalities to create/initialize lists, some most useful functionalities to work with a List in java is listed below.

1- newArrayList, create a new array list

This static generic method is used to create a List collection of elements. An example is given below, it shows how to use it.

final List<Integer> list = Lists.newArrayList(10, 20,3,4,5,6,7,11,2231,546,333);

It has also 2 overloaded version which accepts Iterators and Iterable.

2- partition, partition array list

This method used to partition lists is given equal size and the last part will have partition size or fewer elements.

final List<Integer> list = Lists.newArrayList(10, 20,3,4,5,6,7,11,2231,546,333);

final List<List<Integer>> parts = Lists.partition(list, 2);
int p =1;
for (final List<Integer> list2 : parts) {
System.out.println("Part "+ p++);
System.out.println(list2);
}

Output

Part 1
[10, 20]
Part 2
[3, 4]
Part 3
[5, 6]
Part 4
[7, 11]
Part 5
[2231, 546]
Part 6
[333]

3. reverse, reverse an array list

This method used to reverse a Java array list. An example is given below.

final List<Integer> list = Lists.newArrayList(10, 20,3,4,5,6,7,11,2231,546,333);
final List<Integer> list3 = Lists.reverse(list);
for (final Integer integer : list3) {
System.out.println(integer);
}

 


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.