Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
getcomparator
range

What is Range.getComparator() in Java?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

getComparator() is an instance method of the Range class used to get the comparator. The comparator is used to determine if the objects are within the range.

How to import Range

The definition of Range can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file:


<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
</dependency>

Note: For other versions of the commons-lang package, refer to the Maven Repository.

We can import the Range class like this:


import org.apache.commons.lang3.Range;

Syntax


public Comparator<T> getComparator()

Parameters

This method has no parameters.

Return value

This method returns the comparator being used.

Code

import org.apache.commons.lang3.Range;
import java.util.Comparator;
public class Main{
public static void main(String[] args) {
int fromValue = 100;
int toValue = 200;
Range<Integer> range = Range.between(fromValue, toValue);
Comparator<Integer> comparator = range.getComparator();
System.out.println(comparator != null && comparator instanceof Comparator);
}
}

Explanation

  • In line 4, we define the main class.
  • In line 6, we define the main method.
  • In line 7, we define the minimum/fromValue of the range.
  • In line 8, we define the maximum/toValue of the range.
  • In line 9, we get the Range object with the use of the between method.
  • In line 10, we get the comparator with the use of the getComparator() method.
  • In line 11, we check to see that the returned comparator is not null, and then we implement the Comparator interface.

Output

The output of the code will be:


true

RELATED TAGS

java
communitycreator
getcomparator
range

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring