Java Streams - Sort if Comparator Exists

I have a class where you can optionally specify a Comparator.


Since Comparatorit is optional, I must 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 duplicating code?

Note:
The default is Comparatornot an option, I just want to keep the original order of the values ​​I pass.

In addition, the elements are already displayed at the sorting point, so I cannot somehow refer to the root list of the stream, since I no longer have the original elements.

+4
5

- :

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)
+7

Optional:

Stream<Whatever> stream = [...].stream().map()[...];

List<WhateverElse> result = Optional.ofNullable(comparator)
    .map(stream::sorted)
    .orElse(stream)
    .[...] // <-- go on with the stream pipeline
    .collect(Collectors.toList());
+3

( E ), :

 Comparator<E> NO_SORTING = (one, other) -> 0;

,

.sorted(comparator.orElse(NO_SORTING))
+1

StreamEx

StreamEx(source).[...].chain(s -> comparator == null ? s : s.sorted(comparator)).[...];
+1

, .

static <T, R> R applyFunction(T obj, Function<T, R> f) {
    return f.apply(obj);
}

applyFunction([...].stream().map()[...],
    stream -> comparator == null ? stream : stream.sorted(comparator))
    [...];

.

0

Source: https://habr.com/ru/post/1682370/


All Articles