Monday 18 September 2017

Sorting Collections with Java Lambdas

In Java, the Comparator class is used for sorting collections. In the following examples, we will sort a list of players based on name, surname, name length and last name letter. We will first sort them as we did before, using anonymous inner classes, and then reduce our code using lambda expressions.
In the first example, we will sort our list by name. Using the old way, this looks like this:

String[] players = {"Avijit", "Chintu", "Akshay", "Santosh", "Ritesh", "Avisek", "Krushna", "Surya", "Rudra", "Biswajit"};
 
// Sort players by name using anonymous innerclass
Arrays.sort(players, new Comparator<String>() {
       @Override
       public int compare(String s1, String s2) {
              return (s1.compareTo(s2));
       }
});
 
With lambdas, the same thing can be achieved like this:
// Sort players by name using lambda expression
Comparator<String> sortByName = (String s1, String s2) -> (s1.compareTo(s2));
 
Arrays.sort(players, sortByName);
// or this
Arrays.sort(players, (String s1, String s2) -> (s1.compareTo(s2)));

3 comments:

  1. what is the use of Java Lambda Expression???

    ReplyDelete
  2. Hii Tapan, thanks a ton 4 ur question,
    Ans:A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. ... A lambda expression is the most convenient way to create that delegate.

    ReplyDelete