In this tutorial, we will learn how to Sort an Arraylist in java with example by ascending order using collections class
If you are new to array list refer below link to understand array list
https://beginnersbug.com/arraylist-in-java/
Features
- Sort the specified list into ascending order,
- This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
- The specified list must be modifiable, but need not be resizable.
Syntax
Collections.sort(list);
Example
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SortArrayListExample {
public static void main(String[] args) {
List<String> list = new ArrayList();
list.add("Car");
list.add("Zebra");
list.add("Apple");
list.add("Ball");
System.out.println("Array list values before sorting \n");
for (String string : list) {
System.out.println("Value is " + string);
}
// Below sort method will sort your list
Collections.sort(list);
System.out.println("\nArray list values after sorting \n");
for (String string : list) {
System.out.println("Value is " + string);
}
}
}
Output
Array list values before sorting
Value is Car
Value is Zebra
Value is Apple
Value is Ball
Array list values after sorting
Value is Apple
Value is Ball
Value is Car
Value is Zebra
Reference
https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html
Related Articles
iterate stream with index in Java8
foreach in java8 using streams