Search code examples
javasortingjava-8java-stream

Java Streams - Sort if Comparator exists


I have a class where optionally a Comparator can be specified.


Since the Comparator is optional, I have to evaluate its presence and execute the same stream code, either with sorted() or without:

if(comparator != null) {
    [...].stream().map()[...].sorted(comparator)[...];
} else {
    [...].stream().map()[...];
}

Question:
Is there a more elegant way to do this without the code duplication?

Note:
A default Comparator is not an option, I just want to keep the original order of the values I am streaming.

Besides, the elements are already mapped at the point of sorting, so I can not somehow reference the root list of the stream, as I do not have the original elements anymore.


Solution

  • You can do something like this:

    Stream<Something> stream = [...].stream().map()[...]; // preliminary processing
    if(comparator != null) {
        stream = stream.sorted(comparator); // optional sorting
    }
    stream... // resumed processing, which ends in some terminal operation (such as collect)