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.
[...].stream().map()[...]and choose your IDE "extract variable" refactoring maybe?[...].stream().map()[...].sorted((a,b) -> comparator == null ? 0 : comparator.compare(a,b))[...];Streamclass) and then if a comparator is present, call the sort method of that class? Then collect the result.....sorted(comparator == null? (a,b) -> 0: comparator), not repeating thenull-check in every comparison. Still, it implies an unnecessary sorting process whencomparatorisnull.