The recently popular [Stalin Sort](https://qiita.com/tags/ Stalin Sort), The published java implementation uses a for loop that is not an extension, I thought it was a prehistoric thing because I couldn't hand over the Comparator, so I started writing it myself. I got a bad ride on the way and thought about trying to bind not only for but also if, but it turned out to be a strange code.
For the time being, it also serves as a memorial service
public static <T extends Comparable<? super T>> List<T> stalinSort(List<T> origin) {
return stalinSort(origin, Comparator.naturalOrder());
}
public static <T> List<T> stalinSort(List<T> origin, Comparator<? super T> comparator) {
return origin.stream().reduce(new LinkedList<T>(),
(prev, current) -> Comparator.nullsFirst(comparator).compare(prev.peekLast(), current) <= 0
&& prev.add(current) ? prev : prev,
(a, b) -> {
throw new UnsupportedOperationException();
});
}
Maybe it works.
Recommended Posts