如何合并两个流在Java中?

韦弗:

假设我们有两个流如下:

IntStream stream1 = Arrays.stream(new int[] {13, 1, 3, 5, 7, 9});
IntStream stream2 = Arrays.stream(new int[] {1, 2, 6, 14, 8, 10, 12});
stream1.merge(stream2); // some method which is used to merge two streams.

是否有两个流合并任何方便的方式[13,1,2,3,5,6,7,8,9,10,12,14]使用Java 8流API(顺序并不重要) 。或可我们只在同一时间处理一个流?

此外,如果两个流对象流,怎么可能只保留不同的对象,而无需重写equals()hashCode()方法呢?例如:

public class Student {

    private String no;

    private String name;
}

Student s1 = new Student("1", "May");
Student s2 = new Student("2", "Bob");
Student s3 = new Student("1", "Marry");

Stream<Student> stream1 = Stream.of(s1, s2);
Stream<Student> stream2 = Stream.of(s2, s3);
stream1.merge(stream2);  // should return Student{no='1', name='May'} Student{no='2', name='Bob'}

我们认为两个学生一样,当他们no是相同的,不管name(可能会和玛丽是同一个人,因为他们的数字都是“1”)。

我已经找到了distinct()方法,但这种方法是基于Object#equals()如果我们不能覆盖equals()的方法,我们该如何合并stream1以及stream2到有没有重复的项目一个流?

奥斯曼·d:

@Jigar乔希已经回答了你的问题的第一部分是“如何合并两个IntStream的合一”

您的其他问题:“如何合并两个Stream<T>无覆盖equals()hashCode()方法?” 可以用做toMap收集,即假设你不想要的结果的Stream<T>例:

Stream.concat(stream1, stream2)
      .collect(Collectors.toMap(Student::getNo, 
               Function.identity(), 
               (l, r) -> l, 
               LinkedHashMap::new)
      ).values();

如果你想要的结果作为Stream<T>再一个可以这样做:

 Stream.concat(stream1, stream2)
       .collect(Collectors.collectingAndThen(
               Collectors.toMap(Student::getNo,
                    Function.identity(),
                    (l, r) -> l,
                    LinkedHashMap::new), 
                    f -> f.values().stream()));

这可能是效率不高,因为它可以,但它的另一种方式返回Stream<T>,其中T的项目都是不同的,但没有使用覆盖equals,并hashcode为你所提到的。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章