Pages

Sunday, August 16, 2020

Java 8 – Sorting Stream On Multiple Fields with Comparator.thenComparing()

1.Overview

In this tutorial, You'll learn how to sort the collection or stream of objects on multiple fields in java 8.

In the previous article, I have shown how to implement custom sorting using Collections.sort() method.

Java 8 – Sorting Stream On Multiple Fields with Comparator.thenComparing()


2. Java 8 Comparator Sorting - Multiple Fields Example using Collections.sort()

To sort on a single field then need to use the Comparator.comparing() method from Comparator class.

Sorting based on multiple fields, you first have to create the two comparators using Comparator.comparing() method and next call Comparator.thenComparing() method.

Finally, pass the final comparator to the Collections.sort() method.

Example program to sort multiple fields with Collections.sort() method

package com.javaprogramto.java8.sorting;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SortMultipleFields1 {

    public static void main(String[] args) {


        Book book1 = new Book(105, "Title 5", "Author2", 10);
        Book book2 = new Book(103, "Title 3", "Author1", 15);
        Book book3 = new Book(104, "Title 4", "Author2", 10);
        Book book4 = new Book(101, "Title 1", "Author1", 20);
        Book book5 = new Book(102, "Title 2", "Author2", 15);

        List<Book> unsortredBooksList = Arrays.asList(book1, book2, book3, book4, book5);

        Comparator<Book> idBookComparator = Comparator.comparing(Book::getId);

        Comparator<Book> titleBookComparator = Comparator.comparing(Book::getTitle);

        Comparator<Book> multipleFieldsComparator = idBookComparator.thenComparing(titleBookComparator);

        System.out.println("Unsorted Books List : ");

        for (Book book : unsortredBooksList) {
            System.out.println(book);
        }

        Collections.sort(unsortredBooksList, multipleFieldsComparator);

        System.out.println("After sorting books list : ");


        for (Book book : unsortredBooksList) {
            System.out.println(book);
        }
    }
}

class Book {

    private int id;
    private String title;
    private String author;
    private long price;

    public Book(int id, String title, String author, long price) {
        this.id = id;
        this.title = title;
        this.author = author;
        this.price = price;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public long getPrice() {
        return price;
    }

    public void setPrice(long price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                '}';
    }
}

Output:

Unsorted Books List : 
Book{id=105, title='Title 5', author='Author2', price=10}
Book{id=103, title='Title 3', author='Author1', price=15}
Book{id=104, title='Title 4', author='Author2', price=10}
Book{id=101, title='Title 1', author='Author1', price=20}
Book{id=102, title='Title 2', author='Author2', price=15}
After sorting books list : 
Book{id=101, title='Title 1', author='Author1', price=20}
Book{id=102, title='Title 2', author='Author2', price=15}
Book{id=103, title='Title 3', author='Author1', price=15}
Book{id=104, title='Title 4', author='Author2', price=10}
Book{id=105, title='Title 5', author='Author2', price=10}

Example 2 to sort based on the multiple different fields 

Another example to sort books based on - author and price of books


Comparator<Book> authorComparator = Comparator.comparing(Book::getAuthor);
Comparator<Book> priceComparator = Comparator.comparing(Book::getPrice);

Comparator<Book> multipleFieldsComparator2 = authorComparator.thenComparing(priceComparator);

List<Book> unsortredBooksList2 = Arrays.asList(book1, book2, book3, book4, book5);

System.out.println("Unsorted Books List 2 : ");
for (Book book : unsortredBooksList2) {
    System.out.println(book);
}

Collections.sort(unsortredBooksList2, multipleFieldsComparator);

System.out.println("After sorting books list 2: ");


for (Book book : unsortredBooksList2) {
    System.out.println(book);
}

Output:

Unsorted Books List 2 : 
Book{id=105, title='Title 5', author='Author2', price=10}
Book{id=103, title='Title 3', author='Author1', price=15}
Book{id=104, title='Title 4', author='Author2', price=10}
Book{id=101, title='Title 1', author='Author1', price=20}
Book{id=102, title='Title 2', author='Author2', price=15}
After sorting books list 2: 
Book{id=103, title='Title 3', author='Author1', price=15}
Book{id=101, title='Title 1', author='Author1', price=20}
Book{id=105, title='Title 5', author='Author2', price=10}
Book{id=104, title='Title 4', author='Author2', price=10}
Book{id=102, title='Title 2', author='Author2', price=15}

3. Java 8 Comparator Sorting - Multiple Fields Example using Stream.sorted()

Use the custom compartor to sort on multiple fields with thenComparing() method and call stream.sorted() method in java 8.

Example 3 with Stream.sorted() and Comparator.comparing()

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class SortMultipleFieldsSorted{

    public static void main(String[] args) {


        Book book1 = new Book(105, "Title 5", "Author2", 10);
        Book book2 = new Book(103, "Title 3", "Author1", 15);
        Book book3 = new Book(104, "Title 4", "Author2", 10);
        Book book4 = new Book(101, "Title 1", "Author1", 20);
        Book book5 = new Book(102, "Title 2", "Author2", 15);

        List<Book> unsortredBooksList = Arrays.asList(book1, book2, book3, book4, book5);

        Comparator<Book> idBookComparator = Comparator.comparing(Book::getId);

        Comparator<Book> titleBookComparator = Comparator.comparing(Book::getTitle);

        Comparator<Book> multipleFieldsComparator = idBookComparator.thenComparing(titleBookComparator);

        System.out.println("Unsorted Books List : ");

        for (Book book : unsortredBooksList) {
            System.out.println(book);
        }

        List<Book> sortedList1 = unsortredBooksList.stream().sorted(multipleFieldsComparator).collect(Collectors.toList());

        System.out.println("After sorting books list : ");


        for (Book book : sortedList1) {
            System.out.println(book);
        }

        Comparator<Book> authorComparator = Comparator.comparing(Book::getAuthor);
        Comparator<Book> priceComparator = Comparator.comparing(Book::getPrice);

        Comparator<Book> multipleFieldsComparator2 = authorComparator.thenComparing(priceComparator);

        List<Book> unsortredBooksList2 = Arrays.asList(book1, book2, book3, book4, book5);

        System.out.println("Unsorted Books List 2 : ");
        for (Book book : unsortredBooksList2) {
            System.out.println(book);
        }

        List<Book> sortedList2 = unsortredBooksList2.stream().sorted(multipleFieldsComparator2).collect(Collectors.toList());

        System.out.println("After sorting books list 2: ");


        for (Book book : sortedList2) {
            System.out.println(book);
        }
    }
}

This program produces the output as same as the above program. Instead of Collections.sort() method, used stream.sorted() method. Finally, passed the multipleFieldsComparator1 to thenComparing() method and collected the sorted list into to new List.

4. Conclusion

In this article, you've seen how to sort the list with multiple fields in java 8.

Example programs using Comparator.comparing() method and used Collections.sort() and Stream.sorted(0 method to sort the colletion.

All examples are shown on are over GitHub.

SortMultipleFieldsExample1.java

Java8SortMultipleFields.java

SortMultipleFieldsSorted.java

How to sort ArrayList in java?

Comparator.comparing()

No comments:

Post a Comment

Please do not add any spam links in the comments section.