Java List Collection Tutorial and Examples
Java List Collection Tutorial and Examples
Java List Collection Tutorial and Examples
The Java Collections API provide Java developers with a set of classes and interfaces that makes it
easier to work with collections of objects, e.g. lists, maps, stacks etc.
Rather than having to write your own collection classes, Java provides these ready-to-use collection
classes for you. This tutorial will look closer at the Java Collections, as they are also sometimes
referred to, and more specifically the Java Collections available in Java 8 and later.
Tip
Especially if you’re dynamically resizing a collection of object, favor using a List over a
Java array.
Some additional methods provided by List include:
o add(int index, E element) — Insert an element at a specific location (without
an index argument, new elements are appended to the end)
o get(int index) — Return an element at the specified location
o remove(int index) — Remove an element at the specified location
o set(int index, E element) — Replace the element at the specified location
o subList(int fromIndex, int toIndex) — Returns as a List a modifiable
view of the specified portion of the list (that is, changes to the view actually affect the
underlying list)
Classes Implementing List
Java provides several classes that implement the List interface.
Two are used most commonly:
java.util.ArrayList
An ArrayList is usually your best bet for a List if the values remain fairly static once you’ve
created the list. It’s more efficient than a LinkedList for random access.
java.util.LinkedList
A LinkedList provides better performance than an ArrayList if you’re frequently inserting and
deleting elements, especially from the middle of the collection. But it’s slower than an
ArrayList for random-access.
In the following example, notice the use of the java.util.Collections.sort() static method,
which does an in-place sort of the elements in a List:
java.util.HashSet:: A hash table implementation of the Set interface. The best all-around
implementation of the Set interface, providing fast lookup and updates.
java.util.LinkedHashSet
A hash table and linked list implementation of the Set interface. It maintains the insertion
order of elements for iteration, and runs nearly as fast as a HashSet.
java.util.TreeSet
A red-black tree implementation of the SortedSet interface, maintaining the collection in
sorted order, but slower for lookups and updates.
The Queue Interface
The java.util.Queue interface is a collection designed for holding elements prior to
processing.
o Besides basic Collection operations, queues provide additional insertion, extraction,
and inspection operations.
o Queues can implement FIFO (queue), LIFO (stack), and priority ordering.
o Queues generally do not accept null elements.
Queue operations include:
o Inserting elements: add() and offer()
o Removing and returning elements: remove() and poll()
o Returning elements without removal: element() and peek()
The java.util.concurrent.BlockingQueue interfaces declare additional
blocking put() and take() methods, designed for concurrent access by multiple threads.
java.util.LinkedList
java.util.PriorityQueue
java.util.HashMap:: A hash table implementation of the Map interface. The best all-around
implementation of the Map interface, providing fast lookup and updates.
java.util.LinkedHashMap
A hash table and linked list implementation of the Map interface. It maintains the insertion
order of elements for iteration, and runs nearly as fast as a HashMap.
java.util.TreeMap
A red-black tree implementation of the SortedMap interface, maintaining the collection in
sorted order, but slower for lookups and updates.
o Worse yet, if you were dealing with a collection of objects, say of type Dog, and then
accidentally added an object of an incompatible type, say a Cat, your code could
eventually try to cast the object to the incompatible type, resulting in a runtime
exception.
Java Generics
Java Generics, introduced in Java 5, provide stronger type safety.
Generics allow types to be passed as parameters to class, interface, and method
declarations. For example:
listStrings.add("One");
listStrings.add("Two");
listStrings.add("Three");
listStrings.add("Four");
System.out.println(listStrings);
listStrings.add("Five");
listStrings.add("Six");
listStrings.add("Seven");
listStrings.add("Eight");
System.out.println(listStrings);
Since Java 7, we can remove the type parameter on the right side as follows:
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:
List<Integer> listNumbers = new ArrayList<>(1000);
It’s also possible to construct a list that takes elements from an existing collection, for example:
// OK to add Strings:
listStrings.add("One");
listStrings.add("Two");
listStrings.add("Three");
listStrings.add(123);
linkedNumbers.add(new Integer(123));
linkedNumbers.add(new Float(3.1415));
linkedNumbers.add(new Double(299.988));
linkedNumbers.add(new Long(67000));
We can insert an element into the list at a specified index, for example:
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:
listStrings.addAll(listWords);
For a LinkedList implementation, we can get the first and the last elements like this:
That replaces the 3rd element in the list by the new String “Hi”.
listStrings.remove(2);
o If the specified index is out of range (index < 0 or index >= list size),
a java.lang.IndexOutOfBoundsException is thrown.
o Remove the String element “Two” in the list:
listStrings.remove("Two");
Notes about the remove(Object) method:
o It compares the specified object with the elements in the list using their equals() method,
so if you use your own defined object type, make sure it implements the equals() method
correctly.
o It only removes the first occurrence of the specified element in the list (i.e. if a list contains
duplicate elements, only the first element is removed).
o It returns true if the list contained the specified element, or falseotherwise. Thus it’s
recommended to check return value of this method, for example:
if (listStrings.remove("Ten")) {
System.out.println("Removed");
} else {
listStrings.clear();
System.out.println(element);
while (iterator.hasNext()) {
System.out.println(iterator.next());
while (iterator.hasNext()) {
System.out.println(iterator.next());
if (listStrings.contains("Hello")) {
} else {
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.
Sorting a list
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:
List<String> listStrings = new ArrayList<String>();
listStrings.add("D");
listStrings.add("C");
listStrings.add("E");
listStrings.add("A");
listStrings.add("B");
Collections.sort(listStrings);
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
sourceList.add("A");
sourceList.add("B");
sourceList.add("C");
sourceList.add("D");
destList.add("V");
destList.add("W");
destList.add("X");
destList.add("Y");
destList.add("Z");
Collections.copy(destList, sourceList);
numbers.add(i);
Collections.shuffle(numbers);
Reversing elements in a list
To reverse order of elements in a list, use the Collections.reverse() static method. Here’s a quick
example:
List<Integer> numbers = new ArrayList<Integer>();
Collections.reverse(numbers);
Extracting a portion of a list
The subList(fromIndex, toIndex) allows us to get a portion of the list between the
specified fromIndex(inclusive) and toIndex(exclusive). Here’s an example:
List<String> listNames = Arrays.asList("Tom", "John", "Mary", "Peter", "David", "Alice"
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.
System.out.println(listNames);
System.out.println(listNumbers);
Output:
[1, 3, 5, 7, 9, 2, 4, 6, 8]
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:
Note that the returned array contains copies of elements in the list, which that means we can safely
modify the array without affecting the list.