Sort ArrayList in Java

Price: INR 8,999.00
Price: INR 15,999.00
Was: INR 16,999.00

Let’s see How can you sort the ArryList in Java. By default, the ArrayList’s elements are displayed according to the sequence it is put inside. Sometimes, you may need to sort the ArrayList to make it alphabetically ordered or numerically ordered. In this example, it shows the use of  Collections.sort(‘List’) to sort an ArrayList.

 

Sort ArrayList in ascending order

ArrayList elements are displayed in the same order as they inserted. To sort the ArrayList, we can use the sort()method of the Collections. We can sort the ArrayList like this — Collections.sort(arrayList).

In the above example, arrayList is the object of the ArrayList, what we are passing to the sort() method.

Let’s see, the example of ArrayList. In this example, we are sorting the ArrayList in the ascending order.

Output:

ArrayList befor sort –[15, 20, 25, 5, 12]
ArrayList after ascending Sort –[5, 12, 15, 20, 25]

 

Sort ArrayList in Descending Order

We have seen, how can we sort the arrayList in ascending order. To sort the arrayList in descending order we can use the reverseOrder() method. We will discuss this later because this is the method of comparator class.

Here we will see, How can we sort the arrayList. Here first we will sort the array in ascending order using sort() method later on we will reverse the sorted arrayList using reverse()method.

Let’s understand this with an easy example.

Output:

ArrayList befor sort –[15, 20, 25, 5, 12]
ArrayList after descending Sort –[25, 20, 15, 12, 5]

 

In the above example we have seen, show can we sort the ArrayList in descending order. Later we will discuss these in the tutorial of Comparator class.

Selenium Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

0 Comment

Leave a Reply