iberbeu - 4 months ago 16x

Java Question

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()`

`filter()`

`.filter((obj1, obj2) -> { if (obj1.overlap(obj2)) return true;}) //doesn't work`

Answer

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.

Source (Stackoverflow)

Comments