I’m trying to sort the index of an array based on the value at that index. Eg. [0,2,2,1] would give [0,2,3,1] or [0,3,2,1]
List<Integer> index_map = new LinkedList(Arrays.asList(0,1,2,3)); final int[] sizes = {0,2,1,1}; Collections.sort(index_map, new Comparator<Integer>() { @Override public int compare(Integer a, Integer b) { return sizes[a] < sizes[b] ? -1 : 1; } }); System.out.println(Arrays.toString(sizes)); System.out.println(index_map);
However, using Collections.sort() and the defined comparartor gives [0,3,1,2] instead. Can someone tell me why the output is like that and if there’s a better way to accomplish the target? Thanks
Answer
FIX: you miss th case for equal value and don’t re-implement the comparison code, use the method Integer.compare
directly :
List<Integer> index_map = new LinkedList(Arrays.asList(0,1,2,3)); final int[] sizes = {0,2,1,1}; Collections.sort(index_map, new Comparator<Integer>() { @Override public int compare(Integer a, Integer b) { return Integer.compare(sizes[a],sizes[b]); } });
Improve: it can be reduce with it’s lambda version
Collections.sort(index_map, (a, b) -> Integer.compare(sizes[a], sizes[b]));
Best: use the comparingInt that allows to just specify the value to use to compare, also you can direcrly call sort
on the list :
index_map.sort(Comparator.comparingInt(a -> sizes[a]));