Tuesday, 4 June 2019

Java 8 | How to Implement Comparator using Lambda Expression?

Lambda expression is SAM type (Single Abstract Method), can be used with any interface which contains one method only e.g. Comparator, Comparable, Runnable, Callable, ActionListener and so on.

Before Lambda, Anonymous class was used to implement these one method interfaces. After Java 8, lambdas can be used instead of an anonymous class to avoid boilerplate code.

How to implement Comparator in Java 8 using lambdas?

Java program to implement Comparator using the lambda expression in Java 8:

package com.algorithmforum.java8;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class BookDetail {

      private final String title;
      private final BigDecimal price;

      public Book(String title, BigDecimal price) {
            this.title = title;
            this.price = price;
      }

      public String title() {
            return title;
      }

      public BigDecimal price() {
            return price;
      }

      @Override
      public String toString() {
            return String.format("(%s : %s)", title, price);
      }
}

public class ComparatorUsingLambdas {
      // Comparator to compare Price of books – anonymous class.
      private static Comparator<BookDetail> PRICE_COMPARATOR = new Comparator<BookDetail>() {
            @Override
            public int compare(Book t1, Book t2) {
                  return t1.price().compareTo(t2.price());
            }
      };

      /**
       * Comparator to compare the title of courses using lambda expression of Java 8, in
       * place of anonymous class we don't need the extra line to declare comparator.
       */
      private static Comparator<BookDetail> TITLE_COMPARATOR =
                       (c1, c2) -> c1.title().compareTo(c2.title());

      public static void main(String args[]) {
            // list of book to sort these books based upon their price or title
            List<BookDetail> books = new ArrayList<>();
            books.add(new BookDetail("Spring", new BigDecimal("150")));
            books.add(new BookDetail("NoSQL", new BigDecimal("250")));
            books.add(new BookDetail("Java", new BigDecimal("100")));
            books.add(new BookDetail("Scala", new BigDecimal("400")));

            // sorting objects using Comparator by price
            System.out.println("List of training courses, before sorting");
            System.out.println(books);

            Collections.sort(books, PRICE_COMPARATOR);
            System.out.println("After sorting by price, increasing order");
            System.out.println(books);

            // Lambda expression based comparator.
            System.out.println("Sorting list by the title ");
            Collections.sort(books, TITLE_COMPARATOR);
            System.out.println(books);
      }
}

In this example, we have an object called Books with two attributes title and price, where the title is String and price is BigDecimal because float and double are not good for exact calculations.

Now we have a list of Book and our task is to sort based on their price or based upon their title. To complete these task, we need to create two custom Comparator implementation, one to sort Books by title and other to sort it by price.

To show the stark difference in the number of lines of code you need to do this prior to Java 8 and in JDK 1.8, we have implemented that two Comparator first using Anonymous class and later using the lambda expression and can see that lambdas based Comparator just take one line.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...