Collections Sort || Java Example

In this blog we will see Collection Framework in java  and how to sort elements in java.We have sort() in java.util package by using which we can by default sort the list in ascending and descending order.

Let’s see some sorting mechanisms in collections

 

ArrayList Sorting :

 

Let us consider a String ArrayList and add few names in the ArrayList

List<String> sortString = new ArrayList<String>();

add elements into list

sortString.add("Mike");
sortString.add("Rachel");
sortString.add("Abhishek");
sortString.add("Sam");

 

now implement sorting

Collections.sort(sortString);

Now print the list

System.out.println(sortString);

 

Collection Framework in java

 

now sort the list in reverse order using Collection.reverseOrder()

Collections.sort(sortString,Collections.reverseOrder());

print list

System.out.println(sortString);

Collection Framework in java

 

 

Consider Integer ArrayList

List<Integer> num = new ArrayList<Integer>();

add integers into arraylist

num.add(2);
num.add(1);
num.add(4);
num.add(3);

 

Sort the list

Collections.sort(num);

print list

System.out.println(num);

 

Collection Framework in java

 

now sort the list in reverse order using Collection.reverseOrder()

Collections.sort(num,Collections.reverseOrder());

print list

System.out.println(num);

 

Collection Framework in java

 

If there are any queries on Collection Framework in java let me know in comment section below.

 

Show Buttons
Hide Buttons
Read previous post:
Android tutorial on Dagger 2 || Android Dagger 2 || Data Injection

  Android Dagger 2: Dagger 2 is dependency injection framework, in this tutorial i want to explain Android Dagger 2...

Close