fork(1) download
  1. import java.time.Month;
  2. import java.util.Arrays;
  3. import java.util.stream.IntStream;
  4.  
  5. class Main {
  6.  
  7. public static void main(String[] args) {
  8. var main = new Main();
  9. main.printNewIndexs(new Integer[] { 1, 100, 10, 10000, 1000 });
  10. main.printNewIndexs(new Integer[] { 3, 1, 4, 1, 5, 9, 2 });
  11. main.printNewIndexs(new Integer[] { 0, 1, 0, 1, 0, 1, 0, 1 });
  12. main.printNewIndexs(new String[] { "A","C","B","E","D" });
  13. main.printNewIndexs(new Month[] { Month.MARCH, Month.JANUARY, Month.APRIL, Month.JANUARY, Month.MAY, Month.SEPTEMBER, Month.FEBRUARY });
  14. }
  15.  
  16. private <T extends Comparable<T>> void printNewIndexs(T[] values) {
  17. var originalIndexs = sortOriginalIndex(values);
  18. var newIndexs = new int[originalIndexs.length];
  19. IntStream.range(0, originalIndexs.length)
  20. .forEach(index -> newIndexs[originalIndexs[index]] = index);
  21. System.out.println(Arrays.toString(newIndexs));
  22. }
  23.  
  24. <T extends Comparable<T>> int[] sortOriginalIndex(T[] values) {
  25. return IntStream.range(0, values.length)
  26. .mapToObj(index -> new ValueWithIndex<T>(index, values[index]))
  27. .sorted()
  28. .mapToInt(valueWithIndex -> valueWithIndex.index)
  29. .toArray();
  30. }
  31.  
  32. // static record ValueWithIndex<T extends Comparable<T>>(int index, T value) implements Comparable<ValueWithIndex<T>> {
  33. //
  34. // @Override
  35. // public int compareTo(ValueWithIndex<T> o) {
  36. // return value.compareTo(o.value);
  37. // }
  38. //
  39. // }
  40. static class ValueWithIndex<T extends Comparable<T>> implements Comparable<ValueWithIndex<T>> {
  41.  
  42. final int index;
  43. final T value;
  44. ValueWithIndex(int index, T value) {
  45. this.index = index;
  46. this.value = value;
  47. }
  48. @Override
  49. public int compareTo(ValueWithIndex<T> o) {
  50. return value.compareTo(o.value);
  51. }
  52.  
  53. }
  54.  
  55. }
  56.  
Success #stdin #stdout 0.12s 56288KB
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]