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);
now sort the list in reverse order using Collection.reverseOrder()
Collections.sort(sortString,Collections.reverseOrder());
print list
System.out.println(sortString);
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);
now sort the list in reverse order using Collection.reverseOrder()
Collections.sort(num,Collections.reverseOrder());
print list
System.out.println(num);
If there are any queries on Collection Framework in java let me know in comment section below.