How to compare two IntStreams without collecting or check if all elemnts of one Stream are present in an other stream? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to compare two IntStreams without collecting or check if all elemnts of one Stream are present in an other stream? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Let x be a given stream with certain numbers:

IntStream x = IntStream.of(1,2,3,4,5);

and y a stream to be tested

IntStream y = IntStream.of(5,5,4,3,3,3,3,1,2,2,1,5,3); //result should be true
IntStream y = IntStream.of(5,5,4,3,3,3,3,1,2,2,7,8,9); //result should be false

How do I check that y only consists of the numbers x?

y.distinct().allMatch(i->???)

??? I’m stuck here with what I’m supposed to insert at this point to do the check.

Answer

I differ to the existing answer based on the question stated. If you were to check if all the elements of streamY are that from an existing streamX, you can perform an allMatch and not findAny as:

private boolean intStreamContainsAnother(IntStream streamOfX, IntStream streamOfY) {
    Set<Integer> setOfX = streamOfX.boxed().collect(Collectors.toSet());
    return streamOfY.allMatch(setOfX::contains);
}

Though from the requirements in the question, way to perform that without collecting would not be possible for the reason that the stream could be operated only once.

private boolean intStreamContainsAnother(IntStream streamOfX, IntStream streamOfY) {
    return streamOfY.allMatch(ys -> streamOfX.anyMatch(xs -> xs == ys));
}

We are here to answer your question about How to compare two IntStreams without collecting or check if all elemnts of one Stream are present in an other stream? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji