What would be a good way to compare two Stream
instances in Java 8 and find out whether they have the same elements, specifically for purposes of unit testing?
What I've got now is:
@Test void testSomething() { Stream<Integer> expected; Stream<Integer> thingUnderTest; // (...) Assert.assertArrayEquals(expected.toArray(), thingUnderTest.toArray()); }
or alternatively:
Assert.assertEquals( expected.collect(Collectors.toList()), thingUnderTest.collect(Collectors.toList()));
But that means I'm constructing two collections and discarding them. It's not a performance issue, given the size of my test streams, but I'm wondering whether there's a canonical way to compare two streams.
With Java 8, Collection interface has two methods to generate a Stream. stream() − Returns a sequential stream considering collection as its source. parallelStream() − Returns a parallel Stream considering collection as its source.
Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.
Conclusion: If you have a small list; for loops perform better, if you have a huge list; a parallel stream will perform better. And since parallel streams have quite a bit of overhead, it is not advised to use these unless you are sure it is worth the overhead.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With