What is Range.contains in Java?
Overview
contains() is an instance method of the Range class used to check whether or not the specified element is present in the Range object.
How to import Range
The definition of Range can be found in the Apache Commons Lang package. We can add this package 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 using the following command:
import org.apache.commons.lang3.Range;
Syntax
public boolean contains(final T element)
Parameters
final T element: The element to check.
Return value
This method returns true if the element is within the bounds of the range object. Otherwise, it returns false.
Code
import org.apache.commons.lang3.Range;public class Main{public static void main(String[] args) {int fromValue = 100;int toValue = 200;Range<Integer> range = Range.between(fromValue, toValue);System.out.printf("Range object - %s\n", range);// Example 1int valueToCheck = 4;System.out.printf("%s in [%s, %s] = %s", valueToCheck, fromValue, toValue, range.contains(valueToCheck));System.out.println();// Example 2valueToCheck = 150;System.out.printf("%s in [%s, %s] = %s", valueToCheck, fromValue, toValue, range.contains(valueToCheck));}}
Example 1
Bounds of the Range object - [100..200]element to check - 4
The method returns false because the element to check is not within the bounds of the range object.
Example 2
Bounds of the Range object - [100..200]element to check - 150
The method returns true because the element to check is within the bounds of the range object.
Output
The output of the code will be as follows:
Range object - [100..200]
4 in [100, 200] = false
150 in [100, 200] = true