Java
7 (old way)-
1. Create a comparator
2. Use Collections.sort or pass the comparator to
constructor if you are using treeset or treemap
3. Use the comparator
a)
Option 1- Pass comparator as argument- Collections.sort(collection, comparator);
b)
Option 2- Keep collection sorted always
TreeSet<Integer> treeset = new TreeSet<>(comparator);
TreeMap<Integer,
String> treemap = new TreeMap<>(comparator);
Below are few
examples- note this can be done only for collections which maintain the sorting
order and at the time of initialization you don’t default sorting or order but
some custom sorting order. Below is an example of one of the constructors which
directly accepts a comparator
Java
8- Using lambda expressions
As comparator is a functional interface (consists
of single abstract method), we can use lambda expression to create the sorting
expression. Below is Lamda expression for sorting a list in ascending order
(i1, i2) -> (i1-i2)
// for integers
Ascending sort- Collection.sort
(col, (i1, i2) -> (i1-i2)); // follow regular sequence 1st & then
2nd
Descending sort- Collection.sort
(col, (i1, i2) -> (i2-i1)); //Reverse the sequence, 2nd & then 1st
// for strings
Ascending sort- Collection.sort
(col, (s1, s2) -> (s1.compareTo(s2)); // follow regular sequence 1st
& then 2nd
Descending sort- Collection.sort
(col, (s1, s2) -> (s2.compareTo(s1)); //Reverse the sequence, 2nd &
then 1st
Comments
Post a Comment