Java ArrayList sort() Method · Private Archive
Java ArrayList sort() Method
The sort() method sorts the elements in the dynamic array according to the specified order.
arraylist.sort(Comparator c)
**Note:** arraylist is an object of the ArrayList class.
Parameter Description:
- The syntax of the sort() method is:
Return Value
comparator - the ordering method
Example
The sort() method does not return any value; it only changes the order of elements in the dynamic array list.
Example
import
java.util.ArrayList
;
import
java.util.Comparator
;
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
// Create a dynamic array
ArrayList
<
String
sites
=
new
ArrayList
<>
(
)
;
sites.
add
(
"Runoob"
)
;
sites.
add
(
"Google"
)
;
sites.
add
(
"Wiki"
)
;
sites.
add
(
"Taobao"
)
;
System
.
out
.
println
(
"Website list: "
sites
)
;
System
.
out
.
println
(
Sorting in natural order; the following is the alphabetical order:
sites
)
;
"Unsorted: "
sites.
sort
(
Comparator
.
naturalOrder
(
)
)
;
System
.
out
.
println
(
"After sorting: "
sites
)
;
}
}
The output of the above program is:
网站列表: [Runoob, Google, Wiki, Taobao]
不排序: [Runoob, Google, Wiki, Taobao]
排序后: [Google, Runoob, Taobao, Wiki]
// Sort elements in ascending order
Note this line:
sites.sort(Comparator.naturalOrder());
In the example above, we used the sort() method to sort the dynamic array named sites.
Here, the naturalOrder() method of the Java Comparator interface specifies that elements are sorted in natural order (ascending).
Example
import
java.util.ArrayList
;
import
java.util.Comparator
;
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
// Create a dynamic array
ArrayList
<
String
sites
=
new
ArrayList
<>
(
)
;
sites.
add
(
"Runoob"
)
;
sites.
add
(
"Google"
)
;
sites.
add
(
"Wiki"
)
;
sites.
add
(
"Taobao"
)
;
System
.
out
.
println
(
"Website list: "
sites
)
;
System
.
out
.
println
(
Sorting in natural order; the following is the alphabetical order:
sites
)
;
The Comparator interface also provides a method to sort elements in descending order:
sites.
sort
(
Comparator
.
reverseOrder
(
)
)
;
System
.
out
.
println
(
// Descending order
sites
)
;
}
}
The output of the above program is:
网站列表: [Runoob, Google, Wiki, Taobao]
不排序: [Runoob, Google, Wiki, Taobao]
降序排序: [Wiki, Taobao, Runoob, Google]
"Descending sort: "
Java ArrayList