fork download
  1. import java.time.Month;
  2. import java.util.Arrays;
  3. import java.util.stream.Collectors;
  4. import java.util.stream.IntStream;
  5.  
  6. class Main {
  7.  
  8. public static void main(String[] args) {
  9. var main = new Main();
  10. // 各配列は、Comparableを継承している必要がある。
  11. // Comparableを継承している型の配列であれば、なんでも扱える
  12. main.printNewIndexs(new Integer[] { 1, 100, 10, 10000, 1000 });
  13. main.printNewIndexs(new Integer[] { 3, 1, 4, 1, 5, 9, 2 });
  14. main.printNewIndexs(new Integer[] { 0, 1, 0, 1, 0, 1, 0, 1 });
  15. main.printNewIndexs(new String[] { "A", "C", "B", "E", "D" });
  16. main.printNewIndexs(new Month[] { Month.MARCH, Month.JANUARY, Month.APRIL, Month.JANUARY, Month.MAY, Month.SEPTEMBER, Month.FEBRUARY });
  17. }
  18.  
  19. private <T extends Comparable<T>> void printNewIndexs(T[] values) {
  20. var newIndexs = makeNewIndexs(values);
  21. System.out.println(Arrays.toString(newIndexs));
  22. }
  23.  
  24. private <T extends Comparable<T>> int[] makeNewIndexs(T[] values) {
  25. class ValueWithIndex<U extends Comparable<U>> implements Comparable<ValueWithIndex<T>> {
  26. final int index; // 元のindex情報が必要
  27. final T value;
  28. ValueWithIndex(int index) {
  29. this.index = index;
  30. this.value = values[index];
  31. }
  32. @Override
  33. public int compareTo(ValueWithIndex<T> o) {
  34. return value.compareTo(o.value);
  35. }
  36. }
  37. var sortedList = IntStream.range(0, values.length)
  38. .mapToObj(ValueWithIndex<T>::new)
  39. .sorted()
  40. // .toList();
  41. .collect(Collectors.toList());
  42. var newIndexs = new int[sortedList.size()];
  43. IntStream.range(0, sortedList.size())
  44. .forEach(index -> newIndexs[sortedList.get(index).index] = index);
  45. return newIndexs;
  46. }
  47.  
  48. }
  49.  
Success #stdin #stdout 0.12s 54484KB
stdin
Standard input is empty
stdout
[0, 2, 1, 4, 3]
[3, 0, 4, 1, 5, 6, 2]
[0, 4, 1, 5, 2, 6, 3, 7]
[0, 2, 1, 4, 3]
[3, 0, 4, 1, 5, 6, 2]