This example shows you how we can sort items of an ArrayList
using the Collections.sort()
method. Beside accepting the list object to be sorted we can also pass a Comparator
implementation to define the sorting behaviour such as sorting in descending or ascending order.
package org.kodejava.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ArrayListSortExample {
public static void main(String[] args) {
/*
* Create a collections of colours
*/
List<String> colours = new ArrayList<>();
colours.add("red");
colours.add("green");
colours.add("blue");
colours.add("yellow");
colours.add("cyan");
colours.add("white");
colours.add("black");
/*
* We can sort items of a list using the Collections.sort() method.
* We can also reverse the order of the sorting by passing the
* Collections.reverseOrder() comparator.
*/
Collections.sort(colours);
System.out.println(Arrays.toString(colours.toArray()));
colours.sort(Collections.reverseOrder());
System.out.println(Arrays.toString(colours.toArray()));
}
}
The code will output:
[black, blue, cyan, green, red, white, yellow]
[yellow, white, red, green, cyan, blue, black]
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024