Java List Initialization along with Values Using Guava

This post will introduce various ways to create a Java List using Google Guava library.

Create Mutable List with Values

A mutable list can be modified after we create it, which means we can add, remove, or update its elements.

The Guava way to create a mutable list is quick easy and straightforward

 List<Integer> list1 = Lists.newArrayList(1,2,3,4,5); // prefered way
 List<Integer> list2 = Lists.newArrayList(Arrays.asList(1,2,3,4,5));

Create Immutable List with Values

An immutable list is read-only, which means any modification such as adding new elements, removing an element, or changing an element is not allowd, it will throw an UnsupportedOperationException if we do this.

ImmutableList.of()

 List<Integer> immutableList = ImmutableList.of(1,2,3,4,5); // prefered way

ImmutableList.builder()

 List<Integer> immutableList = ImmutableList.<Integer>builder()
                    .add(1).add(2).add(3).add(4).add(5)
                    .build();

Create Immutable List from Mutable List

ImmutableList.copyOf()

 ImmutableList<Integer> immutableSet = ImmutableList.copyOf(Lists.newArrayList(1,2,3,4,5));

ImmutableList.Builder().addAll()

 ImmutableList<Integer> immutableSet = new ImmutableList.Builder<Integer>()
                    .addAll(Lists.newArrayList(1,2,3,4,5))
                    .build();

Read More