Skip to content
Advertisement

How to check if two streams are disjoint?

I would like to compare to streams, and check if they have 1 or more elements in common (finding 1 is sufficient to stop looking for more). I want to be able to apply this to Streams containing a custom-created class.

For illustration, let’s say I have a class that looks like:

JavaScript

And then I have two lovely streams that look like:

JavaScript

Given that these Streams have 1 Point in common (namely, Point(3, 1)), I would want the final result to be true.

The desired functionality can be pictured as:

JavaScript

Advertisement

Answer

First of all you have to convert your Streams to a Set or List to not get the famous error:

JavaScript

And then you can use anyMatch as this:

JavaScript

Or you can convert only the b Stream to a Set and use:

JavaScript

I would recommend to Set<Coord> instead of Stream<Coord> as param in your method.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement