How to compare two Streams in Java 8
Solution 1:
static void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator();
while(iter1.hasNext() && iter2.hasNext())
assertEquals(iter1.next(), iter2.next());
assert !iter1.hasNext() && !iter2.hasNext();
}
Solution 2:
Collecting the stream under test (as you show) is a straightforward and effective way of performing the test. You may create the list of expected results in the easiest way available, which might not be collecting a stream.
Alternatively, with most libraries for creating mock collaborators, one could mock a Consumer
that "expects" a series of accept()
calls with particular elements. Consume the Stream
with it, and then "verify" that its configured expectations were met.
Solution 3:
Using the elementsEqual
method in the Guava library:
Iterators.elementsEqual(s1.iterator(), s2.iterator())