Friday, May 24, 2024
HomeJavaJava 8 Comparator evaluating() and thenComparing() Instance

Java 8 Comparator evaluating() and thenComparing() Instance

Howdy Java programmers, chances are you’ll know that the JDK 8 has added plenty of
new strategies into the Comparator interface which makes evaluating and
sorting objects in Java very easy. Two such strategies are known as
evaluating() and
thenComparing() which was added
within the
java.util.Comparator interface.
These strategies settle for a key extractor operate and return a Comparator that
can evaluate to that key. The important thing should be
Comparable although like String, Integer, or any Java class which implements
java.lang.Comparable interface,
I imply the important thing should implement Comparable interface. 

Each evaluating() and
thenComparing() means that you can
simply evaluate objects on any area in addition to evaluate them on a number of
fields by chaining comparators. Because the title suggests, you should use the
thenComparing() technique to chain
comparators to match objects on a number of fields and a number of

For instance, you should use evaluating() and thenComparing() to match E book
objects first on writer after which value. you too can select to kind on
growing order of value of reducing order of value. 

General these new Comparator strategies make evaluating objects very easy
and enjoyable as you 
also can cross each
lambda expression
technique reference
to this technique, making it tremendous simple to put in writing customized Comparators on the
fly as proven within the following instance however earlier than that allow’s create a
customized Java object or POJO (Plain Previous Java object to display this
comparability and sorting instance in Java. 
Additionally, previously, I’ve shared Comparator instance for
customized order sorting
and Comparable instance for
pure order soring, in case you are new to Comparator and Comparable interface in Java, you possibly can
examine these articles to get your self aware of Comparator and
Comparable in Java as nicely comparability and sorting of Java

Find out how to evaluate objects utilizing Comparator.evaluating() and
thenComparing() in Java

In an effort to display using Comparator and Comparable in Java 8, we
want a website object. I like books, so I am going to create a E book object with some
fields to display how one can kind an inventory of books utilizing Java 8
options like
lambda expressions
technique reference

Right here is how our E book object will probably be like:

public class E book implements Comparable < E book > {
  personal String title;
  personal String writer;
  personal int value;

  public E book(String title, String writer, int value) {
    this.title = title;
    this.writer = writer;
    this.value = value;

  public String getTitle() {
    return title;

  public String getAuthor() {
    return writer;

  public int getPrice() {
    return value;

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

  public void setAuthor(String writer) {
    this.writer = writer;

  public void setPrice(int value) {
    this.value = value;

  public String toString() {
    return "E book [title=" + title + ", author=" + author + ", price=" +
      price + "]";

  public int compareTo(E book b) {
    int i = this.title.compareTo(b.title);
    if (i != 0) return i;

    i = this.writer.compareTo(b.writer);
    if (i != 0) return i;

    return Integer.evaluate(this.value, b.value);


and right here is the record of Books which we’ll kind on this article:

Record<E book> listOfBooks = new ArrayList<>();
listOfBooks.add(new E book("Efficient Java", "Joshua Bloch", 32));
listOfBooks.add(new E book("Java Puzzlers", "Joshua Bloch", 22));
listOfBooks.add(new E book("Java Concurrency in Follow", 
"Brian Goetz", 42));
listOfBooks.add(new E book("Java SE 8 for Actually Impatient",
 "Cay S. Horstmann", 34));
listOfBooks.add(new E book("Core Java", "Cay S. Horstmann",32));

Now, let’s examine how we are able to kind this record of objects utilizing new options of
Java 8 and new strategies added to the Comparator class just like the
evaluating() and
thenComparing() strategies. 

How to compare objects using comparing() and thenComparing() in Java

Let’s first kind the record of books by authors once more however this time utilizing Comparator.evaluating() technique:

listOfBooks.kind(Comparator.evaluating((E book b) -> b.getAuthor()));

Because the writer is a String, this code will extract the writer as key and
return a Comparator which might evaluate objects by writer. The outcome will probably be
the identical as within the previous instance as proven beneath:

listOfBooks.kind(Comparator.evaluating((E book b) -> b.getAuthor()));
System.out.println("record of books after sorting 
 utilizing evaluating() technique: " 
+ listOfBooks);


record of books after sorting utilizing evaluating technique: 
Book [title=Java Concurrency in Practice, author=Brian Goetz, price=42],
E book [title=Java SE 8 for Really Impatient, author=Cay S. Horstmann,
E book [title=Core Java, author=Cay S. Horstmann, price=32],
E book [title=Effective Java, author=Joshua Bloch, price=32], 
E book [title=Java Puzzlers, author=Joshua Bloch, price=22]

Now, let’s examine one other magic of Java 8, which is able to make it evaluating objects
much more readable, reusable, and composable by utilizing
technique reference
as a substitute of a
lambda expression
Comparator.evaluating() technique as
proven beneath:
listOfBooks.kind(Comparator.evaluating(E book::getAuthor));

You may see that is rather more readable, clear, and concise. You may simply
see that we’re evaluating books primarily based on their writer.  You may as well
use the thenComparing() technique to
evaluate objects on a number of fields. For instance to match books first by
the writer after which on the worth you possibly can simply chain comparators as given in
the next instance

Comparator.evaluating((E book b) -> b.getAuthor())
          .thenComparing((E book b) -> b.getPrice())

One other instance of evaluating and thenComparing to kind objects on a number of fields

Right here is one other instance of utilizing Comparator. evaluating() and thenComparing() strategies to match a Java object into a number of parameters. On this instance, we’ve got three comparators, the primary comparator compares Pupil object on firstName, second evaluate them on each firstName and lastName, and the third comparator compares them on each title and age. For the age area, we’ve got additionally used a reverse comparator which implies they are going to be in contrast in reverse order. 

here’s a full code instance:

import java.util.Comparator;

public class Pupil {
	personal String firstName;
	personal String lastName;
	personal int age;
	Comparator<Pupil> firstNameComparator 
                   = Comparator.evaluating(Pupil::geFirsttName);	 
	Comparator<Pupil> fullNameComparator
                   =  Comparator.evaluating(Pupil::geFirsttName)
	Comparator<Pupil> nameAndAgeComparator 
                   = Comparator.evaluating(Pupil::geFirsttName)

You may see that we’ve got chained comparators on the second and third examples to match Pupil objects on a number of fields. You may chain as many comparators as you need, however code remains to be ver readable, and evaluating logic is apparent.  In case your record incorporates null components then you too can use the nullsFirst() and nullsLast() strategies to place null objects both within the first or final place. 

That is all about find out how to use
evaluating() and
thenComparing() strategies of the
Comparator class to match objects in Java 8. One of the best factor about this
technique is you could cross lambda expression or technique interface to this
technique to match objects.  

If you wish to study extra about superior comparator strategies like
thenComparing() then I extremely suggest you to take a look at my publish about superior comparator and comparable examples in Java, the place I’ve shared find out how to evaluate objects on a number of fields and
totally different orders in Java, together with nulls. 

Different Core Java Articles chances are you’ll like:

  • 20 Examples of Date and Time in Java 8 (tutorial)
  • 5 Free Programs to study Java 8 and 9 (programs)
  • Find out how to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • Find out how to use filter() technique in Java 8 (tutorial)
  • Find out how to kind the map by keys in Java 8? (instance)
  • Find out how to convert Record to Map in Java 8 (resolution)
  • What’s the default technique in Java 8? (instance)
  • 5 Books to Study Java 8 from Scratch (books)
  • Find out how to use Stream class in Java 8 (tutorial)
  • Distinction between summary class and interface in Java 8? (reply)
  • Find out how to kind the might by values in Java 8? (instance)
  • Find out how to be a part of String in Java 8 (instance)
  • 7 Finest Collections and Stream Programs for Java builders (programs)

Thanks for studying this text up to now when you discover this
Instance in Java for evaluating objects of their
pure order then, please Share it with your mates and colleagues. If
you’ve any questions or suggestions then please drop a notice. 



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments