如何在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.

有没有什么方便的方法可以使用 Java 8 流 API 将两个流合并到 [13, 1, 2, 3, 5, 6, 7, 8, 9, 10, 12, 14] (顺序无关紧要) . 还是我们只能同时处理一个流?


此外,如果这两个流是对象流,如何在不覆盖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(所以 May 和 Marry 是同一个人,因为他们的数字都是“1”)。


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


尚方宝剑之说
浏览 327回答 3
3回答

慕神8447489

您可以使用&nbsp;concat()IntStream.concat(stream1,&nbsp;stream2)

DIEA

即“如何将两个 IntStream 合并为一个”。你的另一个问题是“如何在Stream<T>不覆盖equals()andhashCode()方法的情况下合并两个?” 可以使用toMap收集器完成,即假设您不希望结果为Stream<T>. 例子:Stream.concat(stream1, stream2)&nbsp; &nbsp; &nbsp; .collect(Collectors.toMap(Student::getNo,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Function.identity(),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(l, r) -> l,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;LinkedHashMap::new)&nbsp; &nbsp; &nbsp; ).values();如果你想要结果,Stream<T>那么你可以这样做:&nbsp;Stream.concat(stream1, stream2)&nbsp; &nbsp; &nbsp; &nbsp;.collect(Collectors.collectingAndThen(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Collectors.toMap(Student::getNo,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Function.identity(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (l, r) -> l,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; LinkedHashMap::new),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; f -> f.values().stream()));这可能不像它那样有效,但它是另一种返回 a 的方法,Stream<T>其中T项目都是不同的,但不使用覆盖equals,hashcode正如您所提到的。

交互式爱情

对于第一个问题,您可以使用“flatMap”&nbsp; &nbsp; IntStream stream1 = Arrays.stream(new int[] {13, 1, 3, 5, 7, 9});&nbsp; &nbsp; IntStream stream2 = Arrays.stream(new int[] {1, 2, 6, 14, 8, 10, 12});&nbsp; &nbsp; List<Integer> result = Stream.of(stream1, stream2).flatMap(IntStream::boxed)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());&nbsp; &nbsp; //result={13, 1, 3, 5, 7, 9, 1, 2, 6, 14, 8, 10, 12}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java