What is Range.isOverlappedBy in Java?
Overview
isOverlappedBy() is an instance method of the Range class which is used to check if the specified range passed as a parameter overlaps the range on which this method is applied. If there is at least one element in common then the two ranges are said to overlap.
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 boolean isOverlappedBy(final Range<T> otherRange)
Parameters
final Range<T> other: The other range to check
Return value
This method returns true if the specified range passed as a parameter overlaps the range on which this method is applied. 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> range1 = Range.between(fromValue, toValue);fromValue = 150;toValue = 400;Range<Integer> range2 = Range.between(fromValue, toValue);// Example 1System.out.printf("%s.isOverlappedBy(%s) = %s", range1, range2, range1.isOverlappedBy(range2));System.out.println();// Example 2fromValue = 300;toValue = 400;range2 = Range.between(fromValue, toValue);System.out.printf("%s.isOverlappedBy(%s) = %s", range2, range1, range2.isOverlappedBy(range1));System.out.println();}}
Example 1
range1 = [100..200]range2 = [150..400]
The method returns true indicating that range2 is overlapping the range1.
Example 2
range1 = [100..200]range2 = [300..400]
The method returns false indicating that range2 is not overlapping the range1.
Output
The output of the code will be as follows:
[100..200].isOverlappedBy([150..400]) = true
[300..400].isOverlappedBy([100..200]) = false