All I want to do is sort an array of ints by some arbitrary function, criteria(). This is the the only way I've figured out how to do it in Java.
There's a Python implementation of the same thing, for comparison's sake.
| def criteria(x): | |
| return x % 2 != 0 | |
| def sort_test(): | |
| xs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
| ys = sorted(xs, key=criteria) | |
| print 'Got expected results?', ys == [2, 4, 6, 8, 10, 1, 3, 5, 7, 9] | |
| if __name__ == '__main__': | |
| sort_test() |
| import java.util.Arrays; | |
| import java.util.Comparator; | |
| public class SortTest { | |
| static boolean criteria(int x) { | |
| return x % 2 == 0; | |
| } | |
| static void sortTest() { | |
| int[] xs = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; | |
| // Box up the array into Integer objects | |
| Integer[] xObjs = new Integer[xs.length]; | |
| for (int i = 0; i < xs.length; i++) { | |
| xObjs[i] = new Integer(xs[i]); | |
| } | |
| // Sort those Integer objects | |
| Arrays.sort(xObjs, new Comparator<Integer>() { | |
| public int compare(Integer a, Integer b) { | |
| boolean evenA = criteria(a); | |
| boolean evenB = criteria(b); | |
| if (evenA && evenB) { | |
| return 0; | |
| } | |
| return evenA ? -1 : 1; | |
| } | |
| }); | |
| // Unbox them back into primitive ints | |
| int[] ys = new int[xObjs.length]; | |
| for (int i = 0; i < xObjs.length; i++) { | |
| ys[i] = xObjs[i].intValue(); | |
| } | |
| int[] expected = {2, 4, 6, 8, 10, 1, 3, 5, 7, 9}; | |
| System.out.println("Got expected results? " + Arrays.equals(ys, expected)); | |
| } | |
| public static void main(String[] args) { | |
| sortTest(); | |
| } | |
| } |