スキップしてメイン コンテンツに移動

投稿

ラベル(Sorting)が付いた投稿を表示しています

Java: Get Sorted Array Index

As you know, if you would like to sort array, you should use Arrays.sort method. But if you would like to get sorted index, you should use your a brain a bit. In this post, I will show you the code snippet for getting sorted array index. The following is the simplest way to get sorted index. The disadvantages of the following code are autoboxing in compare process and returned array type is not int[] but Integer[]. /** * The most common & general way. But this method use autoboxing and need Integer[] not int[]. */ public static final <T>void sort(T[] array, Comparator<T> comparator, Integer[] sorted) { Arrays.sort(sorted, (i1, i2) -> comparator.compare(array[i1], array[i2])); } To solve these advantage, I wrote following array sort helper class which can get sorted array index as int[] type. You can call getSortedIndex method with source array and comparator as the arguments. The code uses lambda expression which was introduced in Java 8. packa