fit()
methodfit()
is an instance method of the Range
class in Java that fits the given element into the range.
Range
classThe 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;
public T fit(final T element)
final T element
: The element to check.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.
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));}}
range = [100..200]
element = 150
The method returns 150
, as the element is within the bounds of the range.
range = [100..200]
element = 55
The method returns 100
, as the element is out of bounds of the range.
range = [100..200]
element = 300
The method returns 200
, as the element is out of bounds of the range.
The output of the code will be as follows:
[100..200].fit(150) = 150
[100..200].fit(55) = 100
[100..200].fit(300) = 200