between()
is a 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.
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;
public static <T> Range<T> between(final T fromInclusive, final T toInclusive, final Comparator<T> comparator)
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.This method returns an instance of the Range
class.
public static <T extends Comparable<T>> Range<T> between(final T fromInclusive, final T toInclusive)
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;}@Overridepublic String toString() {return "Person{" +"age=" + age +'}';}}public static void main(String[] args) {// Example 1int fromValue = 100;int toValue = 200;Range<Integer> range = Range.between(fromValue, toValue);System.out.println(range);// Example 2Person 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);}}
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.
The output of the code will be as follows:
[100..200][Person{age=4}..Person{age=50}]