CodeJava
Coding Your Passion
- Home>
- Java Core>
- Generics & Collections
Java Generics & Collections: |
|
Java List Collection Tutorial and Examples
DetailsWritten by Nam Ha MinhLast Updated on 14 June 2019 | Print Email
1. Overview of List collection
2. Creating a new list
3. Basic List operations
4. Iterating over elements in a list
5. Searching for an element in a list
6. Sorting a list
7. Copying elements from one list into another
8. Shuffling elements in a list
9. Reversing elements in a list
10. Extracting a portion of a list
11. Converting between Lists and arrays
12. List to Stream
13. Concurrent lists
1. Overview of List collection
List is a fundamental and widely-used collection type in the Java Collections Framework. Basically, a list collection stores elements by insertion order [either at the end or at a specific position in the list]. A list maintains indices of its elements so it allows adding, retrieving, modifying, removing elements by an integer index [zero-based index; the first element is at 0-index, the second at 1-index, the third at 2-index, and so on]. The following picture illustrates a list that stores some String elements:- ArrayList: An implementation that stores elements in a backing array. The arrays size will be automatically expanded if there isnt enough room when adding new elements into the list. Its 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.
- ArrayList quick example:
List listStrings = new ArrayList[]; listStrings.add["One"]; listStrings.add["Two"]; listStrings.add["Three"]; listStrings.add["Four"]; System.out.println[listStrings]; - LinkedList quick example:
List listStrings = new LinkedList[]; listStrings.add["Five"]; listStrings.add["Six"]; listStrings.add["Seven"]; listStrings.add["Eight"]; System.out.println[listStrings];
2. Creating a new list
Its a good practice to declare a list instance with a generic type parameter, for example:List listAnything = new ArrayList[];
List listWords = new ArrayList[];
List listNumbers = new ArrayList[];
List linkedWords = new LinkedList[]; Since Java 7, we can remove the type parameter on the right side as follows:List listNumbers = new ArrayList[];
List linkedWords = new LinkedList[]; 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:List listNumbers = List.of[1, 2, 3, 4, 5, 6];Note that the Listcollection returned by the List.of[] factory method is immutable - meaning that you cant 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:var employees = new ArrayList[];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, its recommended to specify a capacity which is large enough. Lets say, if we know that a list contains around 1000 elements, declare the list as follows:List listNumbers = new ArrayList[1000]; Its also possible to construct a list that takes elements from an existing collection, for example:List listNumberOne; // existing collection
List listNumberTwo = new ArrayList[listNumberOne]; 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:List listStrings = new ArrayList[]; // OK to add Strings: listStrings.add["One"]; listStrings.add["Two"]; listStrings.add["Three"]; // But this will cause compile error listStrings.add[123];Adding elements of sub types of the declared type:List linkedNumbers = new LinkedList[]; 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]; Or add the elements to the list at a specified position:listStrings.addAll[2, listWords]; That inserts all elements of the listWordscollection at 3rd position of the listStrings collection.Retrieving elements from a ListThe get[] method is used to retrieve an element from the list at a specified index. For example, the following code gets an element at 2nd position in the array list and an element at 4th position in the linked list:String element = listStrings.get[1]; Number number = linkedNumbers.get[3]; For a LinkedListimplementation, we can get the first and the last elements like this:LinkedList numbers = new LinkedList[]; // add elements to the list... // get the first and the last elements: Number first = numbers.getFirst[]; Number last = numbers.getLast[]; Note that the getFirst[] and getLast[] methods are specific to the LinkedListclass.Updating elements in a ListUse the set[index, element] method to replace the element at the specified index by the specified element. For example:listStrings.set[2, "Hi"]; That replaces the 3rd element in the list by the new String Hi.Removing elements from a ListTo remove an element from the list, use the remove[index] or remove[Object] method which removes the element at the specified index or by object reference. For example:- Remove the element at the 3rd position in the list:
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:
listStrings.remove["Two"];
- Remove the element at the 3rd position in the list:
- 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.
- 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].
- It returns true if the list contained the specified element, or falseotherwise. Thus its recommended to check return value of this method, for example:
if [listStrings.remove["Ten"]] { System.out.println["Removed"]; } else { System.out.println["There is no such element"]; }
4. Iterating over elements in a list
Basically, we can use the enhanced for loop to iterate through all elements in the list, as follows:for [String element : listStrings] {
System.out.println[element];
} Or use an iterator like this:Iterator iterator = listStrings.iterator[];
while [iterator.hasNext[]] {
System.out.println[iterator.next[]];
} For more list-specific, use a list iterator as shown below:Iterator iterator = linkedNumbers.listIterator[];
while [iterator.hasNext[]] {
System.out.println[iterator.next[]];
} Since Java 8, we can use the forEach[]method like this:listStrings.forEach[s -> System.out.println[s]];For more details and examples, see the tutorial: Java Collections Looping ExampleFor 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.