Skip to content

Instantly share code, notes, and snippets.

@ivan200
Created October 7, 2019 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivan200/a0a6a4cd8b9e841c974223104fec50e2 to your computer and use it in GitHub Desktop.
Save ivan200/a0a6a4cd8b9e841c974223104fec50e2 to your computer and use it in GitHub Desktop.
@SuppressWarnings("unchecked")
@SafeVarargs
public static <T> List<T> sortBy(List<T> list, Function<? super T, ? super Comparable>... function) {
Comparator<T> comparator = (o1, o2) -> {
for (int i = 0; i < function.length; i++) {
Object obj1 = function[i].apply(o1);
Object obj2 = function[i].apply(o2);
int result;
if (obj1 == null || obj2 == null) {
if (obj1 == null && obj2 == null) {
result = 0;
} else {
result = obj1 == null ? 1 : -1; //nullsLast
}
} else {
result = ((Comparable) obj1).compareTo(obj2);
}
if (i == function.length - 1) {
return result;
}
if (result != 0) {
return result;
}
}
return 0;
};
Collections.sort(list, comparator);
return list;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment