Java List Collection Tutorial and Examples
Java List Collection Tutorial and Examples
In this Java list tutorial, I will help you understand the characteristics of list collections, how to use list implementations (ArrayList and
LinkedList) in day-to-day programming and look at various examples of common programming practices when using lists. By following
this tutorial (updated and revised for Java 10) to the end, you will be able to master the List collection in Java.
Table of content:
6. Sorting a list
A list can store objects of any types. Primitive types are automatically converted to corresponding wrapper types, e.g. integer numbers
are converted to Integer objects. It allows null and duplicate elements, and orders them by their insertion order (index).
The following class diagram depicts the primary methods defined in the java.util.List interface:
https://www.codejava.net/java-core/collections/java-list-collection-tutorial-and-examples?tmpl=component&print=1&page=
Java List Collection Tutorial and Examples
The List is the base interface for all list types, and the ArrayList and LinkedList classes are two common List’s
implementations.
ArrayList: An implementation that stores elements in a backing array. The array’s size will be automatically expanded if
there isn’t enough room when adding new elements into the list. It’s possible to set the default size by specifying an initial
capacity when creating a new ArrayList. Basically, an ArrayList offers constant time for the following operations:
size, isEmpty, get, set, iterator, and listIterator; amortized constant time for the add operation; and
linear time for other operations. Therefore, this implementation can be considered if we want fast, random access of the
elements.
LinkedList: An implementation that stores elements in a doubly-linked list data structure. It offers constant time for adding
and removing elements at the end of the list; and linear time for operations at other positions in the list. Therefore, we can
consider using a LinkedList if fast adding and removing elements at the end of the list is required.
Besides ArrayList and LinkedList,Vector class is a legacy collection and later was retrofitted to implement the List
interface. Vector is thread-safe, but ArrayList and LinkedList are not. The following class diagram depicts the inheritance
tree of the List collections:
Java List Collection Tutorial and Examples
The following is a quick example of creating a new ArrayList and LinkedList which hold String objects; add some elements to
them; and then print out the collections:
The compiler is able to infer the actual type parameter from the declaration on the left side.
Since Java 9, you can create a List collection from a fixed set of elements by using the factory method List.of(e1, e2,
e3…). For example:
Note that the List collection returned by the List.of() factory method is immutable - meaning that you can’t add more elements
to it.
Since Java 10, you can shorten the declaration of a List collection by using the var reserved word like this:
The compiler can infer the type of the variable on the left based on the object type on the right side. And var can be used to declare
local variables only.
When creating a new ArrayList using the empty constructor, the list is constructed with an initial capacity of ten. If you are sure
how many elements will be added to the list, it’s recommended to specify a capacity which is large enough. Let’s say, if we know that
a list contains around 1000 elements, declare the list as follows:
It’s also possible to construct a list that takes elements from an existing collection, for example:
The listNumberTwo constructed with copies of all elements from the listNumberOne.
3. Basic List operations: adding, retrieving, updating,
removing elements
Adding elements to a List:
The methods add(Object), add(index, Object) and addAll() are used to add elements to the list. It requires to add
elements of the same type (or sub type) as the type parameter declared by the list. For example:
We can insert an element into the list at a specified index, for example:
1 listStrings.add(1, "Four");
That inserts the String “Four” at the 2nd position in the list.
We can also add all elements of an existing collection to the end of the list: 8/21/2019 Java List Collection Tutorial and Examples
1 listStrings.addAll(listWords);
1 listStrings.addAll(2, listWords);
That inserts all elements of the listWords collection at 3rd position of the listStrings collection.
For a LinkedListimplementation, we can get the first and the last elements like this:
1 LinkedList<Number> numbers = new LinkedList<Number>();
2 // add elements to the list...
3 // get the first and the last elements:
4 Number first = numbers.getFirst();
5 Number last = numbers.getLast();
Note that the getFirst() and getLast() methods are specific to the LinkedList class.
1 listStrings.set(2, "Hi");
That replaces the 3rd element in the list by the new String “Hi”.
1 listStrings.remove(2);
If the specified index is out of range (index < 0 or index >= list size), a java.lang.IndexOutOfBoundsException is
thrown.
Remove the String element “Two” in the list:
1 listStrings.remove("Two");
1 listStrings.clear();
For more details and examples, see the tutorial: Java Collections Looping Example
For more about the forEach iteration method, see the tutorial: The 4 Methods for Iterating Collections in Java
5. Searching for an element in a list
To search for position of a specific element in the list or to know if the list contains the specified element, the following methods can be
used:
boolean contains(Object): returns trueif the list contains the specified element.
int indexOf(Object): returns the index of the first occurrence of the specified element in the list, or -1 if the
element is not found.
int lastIndexOf(Object): returns the index of the last occurrence of the specified element in the list, or -1 if the
element is not found.
Examples:
1 if (listStrings.contains("Hello")) {
2 System.out.println("Found the element");
3 } else {
4 System.out.println("There is no such element");
5 }
6 int firstIndex = linkedNumbers.indexOf(1234);
7 int lastIndex = listStrings.indexOf("Hello");
Note that the above methods compare the elements using their equals() method, so if you define your own type, make sure it
implements the equals() method correctly.
Before Java 8, the simplest way to sort out elements in a list is using the Collections.sort() static method which sorts the
specified list into ascending order, based on the natural ordering of its elements. Here’s an example:
Output:
Note that all elements in the list must implement the Comparableinterface, so if you define your own type, make sure it implements
that interface and its compareTo() method.
Since Java 8, the List interface introduces the sort() method, so you can sort elements in an ArrayList or LinnkedList
directly like this:
For more details and examples, see the article: Sorting List Collections Examples
7. Copying elements from one list into another
The Collections.copyList(dest, src) static method allows us to copy all elements from the source list into the destination
one. Note that the destination list must be large enough to contain the entire source list. Here’s an example:
1 List<String> sourceList = new
2 ArrayList<String>(); sourceList.add("A");
3 sourceList.add("B"); sourceList.add("C");
sourceList.add("D");
4 List<String> destList = new
5 ArrayList<String>(); destList.add("V");
6 destList.add("W"); destList.add("X");
7 destList.add("Y"); destList.add("Z");
8 System.out.println("destList before copy: " + destList);
9 Collections.copy(destList, sourceList);
10 System.out.println("destList after copy: " + destList);
Output:
Note that the sub list is just a view of the original list, so any modifications made on the original list will reflect in the sub list.
The Arrays.asList(T… a) method converts an array of type T to a list of type T. Here’s an example:
Output:
And the Listinterface provides the toArray() method that returns an array of Objects containing all of the elements in the list in
proper sequence (from first to last element). Here’s an example:
For more information about Java stream, read Understand Java Stream API.
Note that you must manually synchronize the returned list when iterating over it, for example:
1 synchronized (safeList) {
2 Iterator<Object>
3 it =
4 safeList.iterator();
while
5 (it.hasNext()) {
6 System.out.println(it.next()); }}
Conclusion:So far you have learned almost everything you need to know about Java list collection for beginners. Now, you're
not only able to use List in your Java program, you also grasp a comprehensive understand about it. For more in-depth learning about
Java collections framework, I recommend you to read the book Java Generics and Collections by Maurice Naftalin and Philip Wadler.
And if you want to learn a full video course about Java programming, I recommend this Java programming masterclass.
For hands-on practice on Java list collection, I recommend you to watch this video tutorial: