# Use Comparator Methods

# Description

In Java 8, new factory methods have been introduced on the Comparator (opens new window) interface to simplify the creation of Comparator objects:

This rule replaces complex lambda expressions which represent Comparator instances by simple invocations of one of the methods listed above.

# Benefits

Reduces the code clutter and improves the readability.

# Tags

# Code Changes

# Natural Order Comparator

Pre

Comparator<User> comparator = (user1, user2) -> user1.compareTo(user2);

Post

Comparator<User> comparator = Comparator.naturalOrder();

# Reversed Order Comparator

Pre

Comparator<User> comparator = (user1, user2) -> user2.compareTo(user1);

Post

Comparator<Integer> comparator = Comparator.reverseOrder();

# Comparing by a Long Property

Pre

Comparator<User> comparator = (user1, user2) -> user1.getUserId().compareTo(user2.getUserId());

Post

Comparator<User> comparator = Comparator.comparingLong(User::getUserId);

# Comparing by a Double Property

Pre

Comparator<User> comparator = (user1, user2) -> user1.getSalary().compareTo(user2.getSalary());

Post

Comparator<User> comparator = Comparator.comparingDouble(User::getSalary);

# Comparing by a Comparable Property

Pre

Comparator<User> comparator = (user1, user2) -> user1.getEmail().compareTo(user2.getEmail());

Post

Comparator<User> comparator = Comparator.comparing(User::getEmail);

# Creating Reversed Comparator by Property

Pre

Comparator<User> comparator = (user1, user2) -> user2.getAge().compareTo(user1.getAge());

Post

Comparator<User> comparator = Comparator.comparingInt(User::getAge).reversed();

# Sorting Collections of Comparables

Pre

users.sort((user1, user2) -> user1.getUserId().compareTo(user2.getUserId()));

Post

users.sort(Comparator.comparingLong(User::getUserId));

You Want To Have Those Changes Done Automatically?

The automatic application of this rule is supported in the following jSparrow version:

# Properties

Property Value
Rule ID UseComparatorMethods
First seen in jSparrow version 3.23.0
Minimum Java version 1.8
Remediation cost 5 min