fork(2) 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. var sortedList = IntStream.range(0, values.length)
  26. .mapToObj(index -> new ValueWithIndex<T>(index, values[index]))
  27. .sorted()
  28. // .toList();
  29. .collect(Collectors.toList());
  30. var newIndexs = new int[sortedList.size()];
  31. IntStream.range(0, sortedList.size())
  32. .forEach(index -> newIndexs[sortedList.get(index).index] = index);
  33. return newIndexs;
  34. }
  35.  
  36. // static record ValueWithIndex<T extends Comparable<T>>(int index, T value) implements Comparable<ValueWithIndex<T>> {
  37. //
  38. // @Override
  39. // public int compareTo(ValueWithIndex<T> o) {
  40. // return value.compareTo(o.value);
  41. // }
  42. //
  43. // }
  44. /**
  45. * ソート対象クラスです。
  46. * @param <T> ソート対象の、Comparableを継承した型
  47. */
  48. static class ValueWithIndex<T extends Comparable<T>> implements Comparable<ValueWithIndex<T>> {
  49.  
  50. final int index; // 元のindex情報が必要
  51. final T value;
  52. ValueWithIndex(int index, T value) {
  53. this.index = index;
  54. this.value = value;
  55. }
  56. @Override
  57. public int compareTo(ValueWithIndex<T> o) {
  58. return value.compareTo(o.value);
  59. }
  60.  
  61. }
  62.  
  63. }
  64.  
Success #stdin #stdout 0.1s 56524KB
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]