This may be an already asked question but I don't find the answer I need.
I have a Set with objects like
public class MyObject {
private LocalDate dateBeginning;
private LocalDate dateEnd;
public boolean overlap(MyObject otherDate) { /*code to check overlapping*/ }
}
I need to check whether the Set contains to elements that overlap each other. In "old-java" I would go through the set twice and check for all combinations that exist and then break or return when I find it.
How can we do this with streams and lambdas in Java 8?
I have already tried with reduction()
and filter()
but none of them seem to work
.filter((obj1, obj2) -> { if (obj1.overlap(obj2)) return true;}) //doesn't work
So, the equals() method is one of the most used and fast ways to compare two sets in Java. The equals() method compares two sets based on the type of the elements, size of the set, and value of the elements.
The equals() method of java. util. Set class is used to verify the equality of an Object with a Set and compare them. The method returns true if the size of both the sets are equal and both contain the same elements.
allMatch() method. The allMatch() method returns true if all elements of the stream matches with the given predicate. It can be used as follows to check if all elements in a list are the same.
Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.
As you said in your question, a possible solution is to loop over the set twice and determine if there are any overlaps. So what we need to determine is if, for any element in the set, we can find any other element that is different and overlaps with it.
With the Stream API, you could thus have the following:
boolean overlap = set.stream()
.anyMatch(
o1 -> set.stream().anyMatch(o2 -> o1 != o2 && o1.overlap(o2))
);
anyMatch
will determine if any elements of the stream satisfies the given condition. The code above is therefore asking if there is one o1
such that there is one o2
different than o1
(we can safely use !=
here since both objects are coming from the same set) and overlapping with it.
Note that this is a O(n²) implementation: the set is traversed twice. This could be possible in a single iteration: at each iteration, an union of the intervals [dateBeginning, dateEnd]
is kept; if at any-time the intersection between the current interval and the accumulated union is non-void, then we know an overlap has been hit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With