What is Range.between() in Java?

between() is a staticthe methods in Java that can be called without creating an object of the class. method of the Range which is used to obtain an instance of Range with the specified minimum and maximum value. The specified minimum and maximum values are inclusive in nature. The method optionally takes in a custom Comparator for custom comparison logic.

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>

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

You can import the Range class as follows:


import org.apache.commons.lang3.Range;

Syntax

public static <T> Range<T> between(final T fromInclusive, final T toInclusive, final Comparator<T> comparator)

Parameters

  • final T fromInclusive: The first value that defines the edge of the range.
  • final T toInclusive: The second value that defines the edge of the range.
  • final Comparator<T> comparator: The comparator used for the comparison.

Return value

This method returns an instance of the Range class.

Overloaded methods

public static <T extends Comparable<T>> Range<T> between(final T fromInclusive, final T toInclusive)

Code

import org.apache.commons.lang3.Range;
import java.util.Comparator;
public class Main{
static class Person{
int age;
public Person(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
'}';
}
}
public static void main(String[] args) {
// Example 1
int fromValue = 100;
int toValue = 200;
Range<Integer> range = Range.between(fromValue, toValue);
System.out.println(range);
// Example 2
Person fromTemp = new Person(4);
Person toTemp = new Person(50);
Range<Person> tempRange = Range.between(fromTemp, toTemp, Comparator.comparingInt(o -> o.age));
System.out.println(tempRange);
}
}

Explanation

  • In the code above, we create different Range objects using the between() method specifying the inclusive values.

  • In the first example, we get the Range object for the integer values 100 and 200. As a custom comparator is not passed as a parameter, the method assumes natural ordering of the elements to determine where the values lie in the range.

  • In the second example, we define a custom class called Person which has age as its attribute. Then we get the Range object for the Person objects with ages 4 and 50. Here, we pass a custom comparator as we define custom comparison logic.

Output

The output of the code will be as follows:

[100..200]
[Person{age=4}..Person{age=50}]