Well, you cannot search in the Stream as long as Stream is an unfinished set of pipelines, i.e. operations. It makes no sense to compare it with such Stream.
The next thing that seems odd to me is probably a typo. I assume you want to search in the stream1
instead of stream2
, hence:
stream2 = stream2.filter(e -> stream1.contains(e));
The only way is to compare a LongStream
with a collection which is optimized for such search. I assume you want to continue the stream1
after you perform the search, so perform these steps:
- Close
stream1
converting it to a List<Long> list1
.
- Perform the search in
stream2
using list1
from stream1
.
- Open
stream1
again for further processing.
LongStream stream1 = ...
LongStream stream2 = ...
List<Long> list1 = stream1.boxed() // list1 from stream1 ..
.collect(Collectors.toList()); // .. which also closes stream1
stream2 = stream2.filter(list1::contains); // perform search
stream1 = list1.stream().mapToLong(l -> l); // open stream1 as LongStream
Edit: Use Set
for better performance as @fps suggests in his answer.