Java

How to Sort ArrayList in Java Ascending Order

In this tutorial, we will see how to sort ArrayList in java using default sorting order.

Sort ArrayList in Java :

To Sort an ArrayList in Java we have an utility method Collections.sort() from Collections class. The sort(List<>) method takes the list object and it sort the list according to the natural order by default it is asscending order.

No matter which type of objets are there in the list, whether String type or Numarical types.

Sort ArrayList :

Creating ArrayList String type:

ArrayList<String> fruitsList = new ArrayList();
fruitsList.add("Banana");
fruitsList.add("Apple");
fruitsList.add("Grapes");
fruitsList.add("Mango");

I am going to sort the above ArrayList in default sorting order.

System.out.println("Before Sorting");
System.out.println("--------------");
fruitsList.forEach((fruit)->System.out.println(fruit));
System.out.println("After Sorting");
System.out.println("--------------");
Collections.sort(fruitsList);
fruitsList.forEach((fruit)->System.out.println(fruit));

Output:

Before Sorting
--------------
Banana
Apple
Grapes
Mango
After Sorting
--------------
Apple
Banana
Grapes
Mango

Creating ArrayList Double type:

Creating Double type ArrayList.

ArrayList<Double> data = new ArrayList();
data.add(0.5);
data.add(0.54);
data.add(0.92);
data.add(0.12);
data.add(0.62);

Sorting Double type ArrayList in default sorting order.

System.out.println("Before Sorting");
System.out.println("--------------");
data.forEach((item)->System.out.println(item));
System.out.println("After Sorting");
System.out.println("--------------");
Collections.sort(data);
data.forEach((item)->System.out.println(item));

Output :

Before Sorting
--------------
0.5
0.54
0.92
0.12
0.62
After Sorting
--------------
0.12
0.5
0.54
0.62
0.92

Happy Learning :)

Found a mistake or something out of date? Tell us →

Written by

chandrashekhar

Founder of onlinetutorialspoint.com. Enterprise architect with 15+ years in healthcare technology, designing and running systems on AWS and Azure. Writes about building real things with AI, local AI hardware and cloud certifications.

Keep reading

Ask a question or leave a comment