Merge and sort multiple Streams java 8

pan*_*_ar 3 sorting merge compare java-8 java-stream

I have multiple streams of Student Object. I have to merge them in sorted order.

class Student {
    private String branch;
    private Integer rollNo;
    private Date doj;
    // Getters and Setters
}
Run Code Online (Sandbox Code Playgroud)

In another class, I have a method

private Stream<Student> mergeAndSort(Stream<Student> s1, Stream<Student> s2, Stream<Student> s3) {
    return Stream.of(s1, s2, s3).sorted(...
        // I tried this logic multiple times but is not working. How can I inject Student comparator here.
        // I have to sort based on branch and then rollNo.
    );
}
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 5

Stream.of(s1, s2, s3) gives you a Stream<Stream<Student>>. In order to get a Stream<Student>, use flatMap:

Stream.of(s1, s2, s3).flatMap(Function.identity()).sorted(...)...
Run Code Online (Sandbox Code Playgroud)

To sort according to the required properties:

return Stream.of(s1, s2, s3)
             .flatMap(Function.identity())
             .sorted(Comparator.comparing(Student::getBranch).thenComparing(Student::getRollNo));
Run Code Online (Sandbox Code Playgroud)

  • @Aomine两种变体各有利弊,因此尚无明确的决定。concat是早期绑定,可以保留大小信息并支持拆分并行流,但是如果嵌套太多,则容易出现堆栈溢出。相比之下,由于缺乏懒惰性,“ flatMap”可用于大量子流,但对于较大的子流则效率较低,[特别是对于较旧的Java版本](/sf/ask/2046056141/)使它甚至可以与无限流中断)。因此,对于合并三个大小未知的流的任务,我将选择`concat`… (2认同)