ArrayList order
Java ArrayList sort()In this tutorial, we will learn about the Java ArrayList sort() method with the help of examples. Show The sort() method sorts the elements in an arraylist according to the specified order. Exampleimport java.util.ArrayList; import java.util.Comparator; class Main { public static void main(String[] args) { // create an ArrayList ArrayList numbers.sort(Comparator.naturalOrder());
System.out.println("Sorted ArrayList: " + numbers);
}
}
// Output: Unsorted ArrayList: [7, 3, 9, -33]
// Sorted ArrayList: [-33, 3, 7, 9]Syntax of ArrayList sort()The syntax of the sort() method is: Here, arraylist is an object of the ArrayList class. sort() ParametersThe sort() method takes a single parameter.
sort() Return ValuesThe sort() method does not return any value. Rather it only changes the order of elements in an arraylist. Example 1: Sort the ArrayList in Natural Orderimport java.util.ArrayList; import java.util.Comparator; class Main { public static void main(String[] args) { // create an ArrayList ArrayList languages.sort(Comparator.naturalOrder());
System.out.println("Sorted ArrayList: " + languages);
}
}Output Unsorted ArrayList: [Python, Swift, C, JavaScript] Sorted ArrayList: [C, JavaScript, Python, Swift]In the above example, we have used the sort() method to sort the arraylist named languages. Notice the line, languages.sort(Comparator.naturalOrder());Here, the naturalOrder() method of the Java Comparator Interface specifies that elements are sorted in natural order (i.e. ascending order). The Comparator interface also provides a method to sort elements in descending order. For example, Example 2: Sort the ArrayList in Reverse Orderimport java.util.ArrayList; import java.util.Comparator; class Main { public static void main(String[] args) { // create an ArrayList ArrayList languages.sort(Comparator.reverseOrder());
System.out.println("Sorted ArrayList: " + languages);
}
}Output Unsorted ArrayList: [Python, Swift, C, JavaScript] Sorted ArrayList: [Swift, Python, JavaScript, C]Here, the reverseOrder() method of the Comparator interface specifies that elements are sorted in reverse order (i.e. descending order). Note: The Collections.sort() method is the more convenient method for sorting an arraylist. |