Sort String Stream with Reversed Comparator in Java



In this article, we will learn how to sort a stream of strings using a reversed comparator in Java. Java 8 introduced the Stream API, which allows powerful operations like sorting using custom comparators.

Java Comparator

A Comparator is a functional interface in Java that defines custom sorting logic. It compares two objects and returns a result based on the comparison.

Java Stream

A Stream is a sequence of elements that can be processed in parallel or sequentially, supporting methods like sorting, filtering, and mapping.

Sorting string stream with a reversed comparator

The following are the steps for sorting a string stream with a reversed comparator ?

  • Step 1: Create a list of strings ? We first create a list of strings to be sorted.
List<String> list = Arrays.asList("Tom", "Jack", "Ryan", "Kevin", "Loki", "Thor");
  • Step 2: Define a comparator for comparison ? We define a comparator to compare strings lexicographically using the compareTo() method.
Comparator<String> comp = (aName, bName) -> aName.compareTo(bName);
  • Step 3: Sort the list using stream with reversed Comparator ? Using the stream() method, we sort the list using the reversed comparator and display the results.
list.stream().sorted(comp.reversed())

Java program to sort string stream with a reversed comparator

The following is an example of sorting string stream with the reversed Comparator ?

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Demo {
	public static void main(String[] args) {
		List<String> list = Arrays.asList("Tom", "Jack", "Ryan", "Kevin", "Loki", "Thor");
		System.out.println("Initial List = "+list);
		System.out.println("Reverse...");
		Comparator<String> comp = (aName, bName) -> aName.compareTo(bName);
		list.stream().sorted(comp.reversed()) .forEach(System.out::println);
	}
}

Output

Initial List = [Tom, Jack, Ryan, Kevin, Loki, Thor]
Reverse...
Tom
Thor
Ryan
Loki
Kevin
Jack
Updated on: 2024-11-23T03:58:06+05:30

508 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements