Tuesday, February 12, 2019

Java 8: Sorting of Collection using lambda Expression


In my previous blog, I have already discussed on Lambda Expression and its Syntax as well as Functional Interface. So, if you are not aware of then I would suggest you to read those blogs before starting this one.


As we know Comparator Interface is also a Functional Interface as it has only one abstract method. In this blog, we will see how we can do sorting using lambda expression.

Let’s start with List and will cover Set, Map as well as Custom Class as well.

  1. List

Sorting of elements on any Array List can be done easily using Collections.sort(…) functions where sort() can take argument as list or with list, you can also pass comparator object.

In below example, we will see how can we sort using comparator and the same task with lambda expression.



Output:

2  2.   Set

Output:


    3. Map

Output:

4. Sorting on custom class with Lambda Expression

/**
 *
 */
package com.waheedtechblog.collection;
import java.util.ArrayList;
import java.util.Collections;
/**
 * Custom class sorting using lambda expression.
 *
 * @author Abdul Waheed
 *
 */
class Book {
private int bookId;
private String bookName;
public Book(int bookId, String bookName) {
this.bookId = bookId;
this.bookName = bookName;
}
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
@Override
public String toString() {
return "Book [bookId=" + bookId + ", bookName=" + bookName + "]";
}
}
public class CustomClassSorting {
public static void main(String[] args) {
Book book1 = new Book(205, "Java");
Book book2 = new Book(300, "Python");
Book book3 = new Book(300, "Spring framework");
Book book4 = new Book(503, "Hibernate");
ArrayList<Book> books = new ArrayList<Book>();
books.add(book1);
books.add(book2);
books.add(book3);
books.add(book4);
System.out.println("Book object natural Sorting\n" + books);
Collections.sort(books,
(b1, b2) -> (b1.getBookId() > b2.getBookId()) ? -1 : (b1.getBookId() < b2.getBookId()) ? 1 : 0);
System.out.println("Book object after Sorting in DESC order\n" + books);
}
}

Output:
Book object natural Sorting
[Book [bookId=205, bookName=Java], Book [bookId=300, bookName=Python], Book [bookId=300, bookName=Spring framework], Book [bookId=503, bookName=Hibernate]]

Book object after Sorting in DESC order
[Book [bookId=503, bookName=Hibernate], Book [bookId=300, bookName=Python], Book [bookId=300, bookName=Spring framework], Book [bookId=205, bookName=Java]]

You can download the source code from Github

Happy Coding...!!!







1 comment: