Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge and sort multiple Streams java 8

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
}

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.
    );
}
like image 493
pankaj_ar Avatar asked Oct 22 '25 09:10

pankaj_ar


1 Answers

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(...)...

To sort according to the required properties:

return Stream.of(s1, s2, s3)
             .flatMap(Function.identity())
             .sorted(Comparator.comparing(Student::getBranch).thenComparing(Student::getRollNo));
like image 148
Eran Avatar answered Oct 25 '25 06:10

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!