$show=/label

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

SHARE:

A quick guide on how to sort the stream on multiple fields in java 8. Comparator Example to sort the collection for different fields.

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()

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,7,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,22,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,81,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,4,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,29,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,66,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,21,String,58,String Programs,9,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 – Sorting Stream On Multiple Fields with Comparator.thenComparing()
Java 8 – Sorting Stream On Multiple Fields with Comparator.thenComparing()
A quick guide on how to sort the stream on multiple fields in java 8. Comparator Example to sort the collection for different fields.
https://1.bp.blogspot.com/-jlSBRqBTRRA/XzkmhF6ZPMI/AAAAAAAAC6Y/RApOEFSSCh8rRoIA0TBi1kHyHzy5wAq_gCLcBGAsYHQ/w640-h355/Java%2B8%2B%25E2%2580%2593%2BSorting%2BStream%2BOn%2BMultiple%2BFields%2Bwith%2BComparator.thenComparing%2528%2529.png
https://1.bp.blogspot.com/-jlSBRqBTRRA/XzkmhF6ZPMI/AAAAAAAAC6Y/RApOEFSSCh8rRoIA0TBi1kHyHzy5wAq_gCLcBGAsYHQ/s72-w640-c-h355/Java%2B8%2B%25E2%2580%2593%2BSorting%2BStream%2BOn%2BMultiple%2BFields%2Bwith%2BComparator.thenComparing%2528%2529.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/08/java-8-sorting-stream-on-multiple-fields.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/08/java-8-sorting-stream-on-multiple-fields.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content