How to compare two Streams in Java 8

By | March 24, 2023

To compare two streams in Java 8, you can use the Stream.allMatch() method along with a lambda expression to define the comparison criteria.

Here’s an example code snippet that demonstrates this approach:

List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5);

List<Integer> list2 = Arrays.asList(1, 2, 3, 4, 5);

boolean isEqual = list1.stream()

        .allMatch(list2::contains);

System.out.println(isEqual); // Output: true

In the above example, we have two lists list1 and list2 with the same elements. We first create streams from both lists using the stream() method. Then, we use the allMatch() method on the stream of list1 and pass a lambda expression that checks if each element in list1 is also present in list2. We use the contains() method on list2 to check for the presence of each element. Finally, we assign the result of the comparison to the isEqual variable and print it to the console.

If the two streams have the same elements in the same order, you can use the Stream.iterate() method to iterate over both streams in parallel and compare the elements at each index.

Here’s an example code snippet that demonstrates this approach:

Stream<Integer> stream1 = Stream.of(1, 2, 3, 4, 5);

Stream<Integer> stream2 = Stream.of(1, 2, 3, 4, 5);

boolean isEqual = Stream.iterate(0, i -> i + 1)

        .limit(Math.min(stream1.count(), stream2.count()))

        .allMatch(i -> stream1.skip(i).findFirst().equals(stream2.skip(i).findFirst()));

System.out.println(isEqual); // Output: true

In the above example, we use the Stream.iterate() method to create a stream of indices starting from 0 and incrementing by 1. We limit the stream to the minimum of the sizes of both streams using the limit() method to ensure that we only iterate over the common elements in both streams. Then, for each index, we use the skip() method on both streams to skip the elements at the previous indices, and use the findFirst() method to get the first element at the current index. Finally, we use the equals() method to compare the elements at each index, and use the allMatch() method to check if all the comparisons are true.

Leave a Reply

Your email address will not be published. Required fields are marked *