What is Range.fit() in Java?
The fit() method
fit() is an instance method of the Range class in Java that fits the given element into the range.
- If the provided element is within the bounds of the range, the method returns the given element.
- If the element is out of bounds of the range, then the method returns the closest element in the given range.
How to import the Range class
The definition of the Range class 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>
Please refer to the Maven Repository for other versions of the commons-lang package.
You can import the Range class as follows:
import org.apache.commons.lang3.Range;
Syntax
public T fit(final T element)
Parameters
final T element: The element to check.
Return value
This method returns the minimum value of the range, the given element, or the maximum value of the range, depending on the element’s location relative to the range.
Code
import org.apache.commons.lang3.Range;class Main{public static void main(String[] args) {int fromValue = 100;int toValue = 200;Range<Integer> range = Range.between(fromValue, toValue);// Example 1int element = 150;System.out.printf("%s.fit(%s) = %s", range, element, range.fit(element));System.out.println();// Example 2element = 55;System.out.printf("%s.fit(%s) = %s", range, element, range.fit(element));System.out.println();// Example 3element = 300;System.out.printf("%s.fit(%s) = %s", range, element, range.fit(element));}}
Example 1
range = [100..200]element = 150
The method returns 150, as the element is within the bounds of the range.
Example 2
range = [100..200]element = 55
The method returns 100, as the element is out of bounds of the range.
Example 3
range = [100..200]element = 300
The method returns 200, as the element is out of bounds of the range.
Output
The output of the code will be as follows:
[100..200].fit(150) = 150
[100..200].fit(55) = 100
[100..200].fit(300) = 200