Java List is an ordered collection. Java List is an interface that extends Collection interface. Java List provides control over the position where you can insert an element. You can access elements by their index and also search elements in the list.
Some of the important points about Java List are;
Java List interface extends Collection interface. Collection interface externs Iterable interface. Some of the most used List implementation classes are ArrayList, LinkedList, Vector, Stack, CopyOnWriteArrayList. AbstractList provides a skeletal implementation of the List interface to reduce the effort in implementing List.
Some of the useful Java List methods are;
Some of the default methods added to List in Java 8 are;
We can use Arrays class to get the view of array as list. However we won’t be able to do any structural modification to the list, it will throw java.lang.UnsupportedOperationException. So the best way is to use for loop for creating list by iterating over the array. Below is a simple example showing how to convert java array to list properly.
package com.journaldev.examples;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ArrayToList {
public static void main(String[] args) {
String[] vowels = {"a","e","i","o","u"};
List<String> vowelsList = Arrays.asList(vowels);
System.out.println(vowelsList);
/**
* List is backed by array, we can't do structural modification
* Both of the below statements will throw java.lang.UnsupportedOperationException
*/
//vowelsList.remove("e");
//vowelsList.clear();
//using for loop to copy elements from array to list, safe for modification of list
List<String> myList = new ArrayList<>();
for(String s : vowels){
myList.add(s);
}
System.out.println(myList);
myList.clear();
}
}
Choose any of the above methods based on your project requirements.
A simple example showing the correct way to convert a list to array.
package com.journaldev.examples;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListToArray {
public static void main(String[] args) {
List<String> letters = new ArrayList<String>();
// add example
letters.add("A");
letters.add("B");
letters.add("C");
//convert list to array
String[] strArray = new String[letters.size()];
strArray = letters.toArray(strArray);
System.out.println(Arrays.toString(strArray)); //will print "[A, B, C]"
}
}
There are two ways to sort a list. We can use Collections class for natural sorting or we can use List sort() method and use our own Comparator for sorting. Below is a simple example for java list sorting.
package com.journaldev.examples;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class ListSortExample {
public static void main(String[] args) {
List<Integer> ints = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < 10; i++) ints.add(random.nextInt(1000));
//natural sorting using Collections class
Collections.sort(ints);
System.out.println("Natural Sorting: "+ints);
//My custom sorting, reverse order
ints.sort((o1,o2) -> {return (o2-o1);});
System.out.println("Reverse Sorting: "+ints);
}
}
A sample output is given below. Since I am using Random for generating list elements, it will be different every time.
Natural Sorting: [119, 273, 388, 450, 519, 672, 687, 801, 812, 939]
Reverse Sorting: [939, 812, 801, 687, 672, 519, 450, 388, 273, 119]
Most common operations performed on java list are add, remove, set, clear, size etc. Below is a simple java list example showing common method usage.
package com.journaldev.examples;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListExample {
public static void main(String args[]) {
List<String> vowels= new ArrayList<String>();
//add example
vowels.add("A");
vowels.add("I");
//let's insert E between A and I
vowels.add(1,"E");
System.out.println(vowels);
List<String> list = new ArrayList<String>();
list.add("O");list.add("U");
//appending list elements to letters
vowels.addAll(list);
System.out.println(vowels);
//clear example to empty the list
list.clear();
//size example
System.out.println("letters list size = "+vowels.size());
//set example
vowels.set(2, "E");
System.out.println(vowels);
//subList example
vowels.clear();vowels.add("E"); vowels.add("E");vowels.add("I"); vowels.add("O");
list = vowels.subList(0, 2);
System.out.println("letters = "+vowels+", list = "+list);
vowels.set(0, "A");
System.out.println("letters = "+vowels+", list = "+list);
list.add("U");
System.out.println("letters = "+vowels+", list = "+list);
}
}
Output of above java list example program is;
[A, E, I]
[A, E, I, O, U]
letters list size = 5
[A, E, E, O, U]
letters = [E, E, I, O], list = [E, E]
letters = [A, E, I, O], list = [A, E]
letters = [A, E, U, I, O], list = [A, E, U]
Below is a simple example showing how to iterate over list in java.
package com.journaldev.examples;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ListIteratorExample {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
for(int i=0; i<5; i++) list.add(i);
Iterator<Integer> iterator = list.iterator();
//simple iteration
while(iterator.hasNext()){
int i = (int) iterator.next();
System.out.print(i + ", ");
}
System.out.println("\n"+list);
//modification of list using iterator
iterator = list.iterator();
while(iterator.hasNext()){
int x = (int) iterator.next();
if(x%2 ==0) iterator.remove();
}
System.out.println(list);
//changing list structure while iterating
iterator = list.iterator();
while(iterator.hasNext()){
int x = (int) iterator.next(); //ConcurrentModificationException here
if(x==1) list.add(10);
}
}
}
Output of above java list iterator program is;
0, 1, 2, 3, 4,
[0, 1, 2, 3, 4]
[1, 3]
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at com.journaldev.examples.ListIteratorExample.main(ListIteratorExample.java:34)
That’s all of a quick roundup on List in Java. I hope these Java List examples will help you in getting started with List collection programming.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Sign up for Infrastructure as a Newsletter.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
comprehensive
- venkatesh
if i have method like public static List getStudent (List, String type) { List list =new ArrayList() ; list. add(new Student (“java”, 36); } return list ; how to call this method in main because in parameter List throwing error
- SyedVaseemAkram
Thank you so much very important information good job I like this article. Looking to convert List to String Java? Let’s have a glance at how to convert a Java Collections List of elements to a String in Java. Basically List in Java is an ordered collection or a default sequence. List accepts duplicate elements unlike Map doesn’t accept duplicate values and also holds the thing in key-value pairs. We can print the contents of a listing element during a readable form while debugging the code, which is useful . List interface and String class were a part of Java object-oriented programming API. From below Java program, lets see how to convert Java list to string array using toString method. We are passing integer argument (number) to create java string array using Arrays asList() method. In other words, we are passing list of integers as array to list.
- JAMES C. EATON
One of my interview questions is how does list know when to throw concurrent modification exception. A 1 minute walkthrough of Arraylist class would help in answering this question
- Praveen
hi, I want to get the value from List having values as mentioned below: [xyz,abc] [wer,tyu] [edc,rfv] Where [xyz,abc] is first element of list. I want to access xyz and abc individually.
- Sweta Sharma