$show=/label

Java 8 Comparator Comparing Reverse Order

SHARE:

A quick guide to reverse the collection using the Comparator interface in java with Comparator.reverseOrder() and Comparator.reversed() methods.

 

1. Overview

In this tutorial, We'll learn how to use a comparator to sort the collection in reverse order.

In Java 8, Comparator interface is added with the reverse() method to reverse the collection using the existing comparator instead of creating another custom comparator.

First, let us learn how to reverse the comparator for comparing the objects from the collection before java 8 and next using Java 8 Comparator new methods.


Java 8 Comparator Comparing Reverse Order



2. Before java 8


In the older version of JDK 1.8, we can not reverse the comparator operations using any built-in API methods but we can reverse the list of objects using reverse() method from the Collections.

This does not use the comparator interface as underlying logic. It just uses the ListIterator to reverse the list.

Example 1
package com.javaprogramto.java8.comparator.reverse;

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

public class ComparatorReverse {

	public static void main(String[] args) {

		List<String> list = Arrays.asList("1", "3", "2");

		System.out.println("Original list - " + list);
		Collections.reverse(list);
		System.out.println("Reversed list - " + list);

	}
}

Output
Original list - [1, 3, 2]
Reversed list - [2, 3, 1]


3. Using Java 8 Comparator.reverseOrder()


Comparator interface has the method that is reverseOrder() from java 8.

Comparator.reverseOrder() method is used to get the comparator that imposes the reverse of the natural ordering.

reverseOrder() method internally creates the instance of the ReverseComparator static inner class which makes the call to the Comparator.naturalOrder() method.


Example 2
package com.javaprogramto.java8.comparator.reverse;

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

public class ComparatorReverse2 {

	public static void main(String[] args) {

		List<String> list = Arrays.asList("1", "3", "2");

		System.out.println("Original list - " + list);

		List<String> sortedList = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

		System.out.println("Sorted list - " + sortedList);

	}
}

Output
Original list - [1, 3, 2]
Sorted list - [3, 2, 1]

In the above code, we did not create any comparator to sort the strings in descending order. We have used the Comparator.reverseOrder() method to create the default comparator for the reverse order.

Example 3

What happens if the reverseOrder() method is called twice? (calling reverseOrder() on the result of first call to reverseOrder()).

Look at the below example, you will get a clear idea of what trying to do.

public class ComparatorReverse3 {

	public static void main(String[] args) {

		List<String> list = Arrays.asList("1", "3", "2");

		System.out.println("Original list - " + list);

		List<String> result1 = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
		System.out.println("result 1 " + result1);

		List<String> result2 = result1.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
		System.out.println("result 2 - " + result2);

	}
}


Output
Original list - [1, 3, 2]
result 1 [3, 2, 1]
result 2 - [3, 2, 1]

From the result, we can understand that multiple calls to the reverseOrder() method do not change the output. It produces the same output always.


4. Java 8 Comparator.reverseOrder() with Custom Objects


Example 4
package com.javaprogramto.java8.comparator.reverse;

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

public class ComparatorReverse6 {

	public static void main(String[] args) {

		List<Teacher2> Teacher2s = new ArrayList<>();

		Teacher2s.add(new Teacher2("Rajesh", "Science", 10));
		Teacher2s.add(new Teacher2("Mahesh", "Mathematics", 5));
		Teacher2s.add(new Teacher2("Suresh", "English", 10));
		Teacher2s.add(new Teacher2("Rakesh", "Science", 3));
		Teacher2s.add(new Teacher2("Ramesh", "Mathematics", 8));

		System.out.println("Original Teacher2s list - ");
		Teacher2s.forEach(t -> System.out.println(t.getSubject()));

		List<Teacher2> sortBynameList = Teacher2s.stream().sorted()
				.collect(Collectors.toList());

		System.out.println("\nSorted by subject ascending order");
		sortBynameList.forEach(t -> System.out.println(t.getSubject()));

		sortBynameList = Teacher2s.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

		System.out.println("\nSorted by subject descending order ");
		sortBynameList.forEach(t -> System.out.println(t.getSubject()));
	}
}


package com.javaprogramto.java8.comparator.reverse;

public class Teacher2 implements Comparable<Teacher2>{

	String name;
	String subject;
	int experience;

	public Teacher2(String name, String subject, int experience) {
		super();
		this.name = name;
		this.subject = subject;
		this.experience = experience;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public int getExperience() {
		return experience;
	}

	public void setExperience(int experience) {
		this.experience = experience;
	}

	@Override
	public int compareTo(Teacher2 o) {
		return this.getSubject().compareTo(o.getSubject());
	}
}

Output
Original Teacher2s list - 
Science
Mathematics
English
Science
Mathematics

Sorted by subject ascending order
English
Mathematics
Mathematics
Science
Science

Sorted by subject descending order 
Science
Science
Mathematics
Mathematics
English


5. Using java 8 Comparator.reverse()


Comparator.reverse() method is used to reverse the existing comparator sorting behaviour.

This reverse() method must be used on comparator instances only.

Example 5
package com.javaprogramto.java8.comparator.reverse;

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

public class ComparatorReverse4 {

	public static void main(String[] args) {

		List<String> list = Arrays.asList("100", "3", "20");

		System.out.println("Original list - " + list);

		Comparator<String> sortByLength = Comparator.comparing(String::length);

		List<String> sortedList = list.stream().sorted(sortByLength).collect(Collectors.toList());

		System.out.println("Sorted by length ascending order - " + sortedList);

		Comparator<String> sortByLengthReverse = sortByLength.reversed();

		sortedList = list.stream().sorted(sortByLengthReverse).collect(Collectors.toList());

		System.out.println("Sorted by length descending order - " + sortedList);
	}
}


Output
Original list - [100, 3, 20]
Sorted by length ascending order - [3, 20, 100]
Sorted by length descending order - [100, 20, 3]


6. Java 8 Comparator reverse() With Custom Objects


The comparator can be created with the help of lambda expressions. Look at the simple examples of how to create the comparator with Lambda?

In this section, we will learn how to use reverse() method on custom objects to reverse the existing sorting logic. This will help to reduce the rewriting of the same code.

Example 6
package com.javaprogramto.java8.comparator.reverse;

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

public class ComparatorReverse5 {

	public static void main(String[] args) {

		List<Teacher> teachers = new ArrayList<>();

		teachers.add(new Teacher("Rajesh", "Science", 10));
		teachers.add(new Teacher("Mahesh", "Mathematics", 5));
		teachers.add(new Teacher("Suresh", "English", 10));
		teachers.add(new Teacher("Rakesh", "Science", 3));
		teachers.add(new Teacher("Ramesh", "Mathematics", 8));

		System.out.println("Original teachers list - ");
		teachers.forEach(t -> System.out.println(t.getName()));

		Comparator<Teacher> sortByName = (t1, t2) -> t1.getName().compareTo(t2.getName());

		List<Teacher> sortBynameList = teachers.stream().sorted(sortByName).collect(Collectors.toList());

		System.out.println("\nSorted by name ascending order");
		sortBynameList.forEach(t -> System.out.println(t.getName()));

		Comparator<Teacher> sortByNameReverse = sortByName.reversed();

		sortBynameList = teachers.stream().sorted(sortByNameReverse).collect(Collectors.toList());

		System.out.println("Sorted by name descending order ");
		sortBynameList.forEach(t -> System.out.println(t.getName()));
	}
}

Output
Original teachers list - 
Rajesh
Mahesh
Suresh
Rakesh
Ramesh

Sorted by name ascending order
Mahesh
Rajesh
Rakesh
Ramesh
Suresh

Sorted by name descending order 
Suresh
Ramesh
Rakesh
Rajesh
Mahesh


7. Conclusion


In this article, we have seen how to use the Comparator reverseOrder() and reverse() method in java 8 with examples.

Use Comparator reverseOrder() method when working with the collection of wrapper class objects because these are implemented by the Comparable interface. And also reverseOrder() method is used to List of custom objects which implements the Comparable interfaces.

If user-defined classes are not implemented in any Comparator or Comparable interface then better to custom comparators with Comparator.reveres() method which is specific to the use case.







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,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,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,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 Comparator Comparing Reverse Order
Java 8 Comparator Comparing Reverse Order
A quick guide to reverse the collection using the Comparator interface in java with Comparator.reverseOrder() and Comparator.reversed() methods.
https://blogger.googleusercontent.com/img/a/AVvXsEhBlc4dSgd4ZT7ud1_X71UYHgDhHUPW5P_D0PKZ7zGOU6BA-_1pPZRZ4PO9OQmi_odeGaxVBG8YITZXUnT5cSlclr4eagFLMWFUwFxWxZZ-xrT6yjB2bWHggj2IfNB0kxmjr6IwNjRFwhfZ5JSziYgANadgBb5i24kZzJi9ug397EFGCDanRn9fpTMb=w640-h396
https://blogger.googleusercontent.com/img/a/AVvXsEhBlc4dSgd4ZT7ud1_X71UYHgDhHUPW5P_D0PKZ7zGOU6BA-_1pPZRZ4PO9OQmi_odeGaxVBG8YITZXUnT5cSlclr4eagFLMWFUwFxWxZZ-xrT6yjB2bWHggj2IfNB0kxmjr6IwNjRFwhfZ5JSziYgANadgBb5i24kZzJi9ug397EFGCDanRn9fpTMb=s72-w640-c-h396
JavaProgramTo.com
https://www.javaprogramto.com/2021/12/java-8-comparator-comparing-reverse.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2021/12/java-8-comparator-comparing-reverse.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