Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two Streams in Java 8

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.

like image 726
Vlad Avatar asked Jan 15 '16 19:01

Vlad


People also ask

What are two types of streams in Java 8?

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.

What does .stream do in Java?

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.

Is parallel stream faster than for loop?

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.


1 Answers

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(); } 
like image 81
ZhongYu Avatar answered Sep 22 '22 11:09

ZhongYu