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. // record ValueWithIndex<T extends Comparable<T>>(int index, T value) implements Comparable<ValueWithIndex<T>> {
  26. // @Override
  27. // public int compareTo(ValueWithIndex<T> o) {
  28. // return value.compareTo(o.value);
  29. // }
  30. //
  31. // }
  32. // recordはTでも通ったが、classは一部をT以外にしないと通らない
  33. class ValueWithIndex<U extends Comparable<U>> implements Comparable<ValueWithIndex<T>> {
  34. final int index; // 元のindex情報が必要
  35. final T value;
  36. ValueWithIndex(int index, T value) {
  37. this.index = index;
  38. this.value = value;
  39. }
  40. @Override
  41. public int compareTo(ValueWithIndex<T> o) {
  42. return value.compareTo(o.value);
  43. }
  44. }
  45. var sortedList = IntStream.range(0, values.length)
  46. .mapToObj(index -> new ValueWithIndex<T>(index, values[index]))
  47. .sorted()
  48. // .toList();
  49. .collect(Collectors.toList());
  50. var newIndexs = new int[sortedList.size()];
  51. IntStream.range(0, sortedList.size())
  52. .forEach(index -> newIndexs[sortedList.get(index).index] = index);
  53. return newIndexs;
  54. }
  55.  
  56. }
  57.  
Success #stdin #stdout 0.09s 54480KB
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]