How to compare two Streams in Java 8

后端 未结 6 1848
眼角桃花
眼角桃花 2020-12-03 06:38

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?<

6条回答
  •  一向
    一向 (楼主)
    2020-12-03 07:08

    How to Compare Two Streams in java 8 and above: with the example of Comparing IntStream

    package com.techsqually.java.language.generics.basics;
    
    import java.util.Iterator;
    import java.util.stream.IntStream;
    import java.util.stream.Stream;
    
    public class TwoStreamComparision {
    
        public static void main(String[] args) {
    
            String a = "Arpan";
            String b = "Arpen";
    
            IntStream s1 =  a.chars();
            IntStream s2  = b.chars();
    
            Iterator s1It = s1.iterator();
            Iterator s2It = s2.iterator();
    
            //Code to check how many characters are not equal in both the string at their Respective Position
            int count = 0;
            while (s2It.hasNext()){
                if (!s1It.next().equals(s2It.next())){
                    count++;
                }
            }
            System.out.println(count);
        }
    }
    

提交回复
热议问题