Created
October 7, 2019 08:46
-
-
Save ivan200/a0a6a4cd8b9e841c974223104fec50e2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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