【问题标题】:Java sorting indices in a new arrayJava对新数组中的索引进行排序
【发布时间】:2020-09-30 17:38:11
【问题描述】:

假设我有一个数组 test-

int[] test={5,4,3,2,1};

现在,当我按升序对该数组进行排序时,我想将元素的索引存储在一个新数组中。因此,按升序对上述数组进行排序应该会创建一个新数组,其值为 {4,3,2,1,0} 在 C++ 中,这是代码--

vector<int> order(n);
iota(order.begin(),order.end(),0);
sort(order.begin(),order.end(),[&](int i,int j){
     return test[i]<=test[j];
});

我想知道如何使用比较器类在 Java 中实现这一点

【问题讨论】:

  • 您应该使用 ArrayList 而不是 Vector,据我了解,它已被弃用多年。

标签: java arrays sorting comparator


【解决方案1】:

您可以通过这种方式使用Comparator.comparing按该索引的值对所有索引进行排序

int[] res = IntStream.range(0, test.length)
                     .boxed()
                     .sorted(Comparator.comparing(e -> test[e]))
                     .mapToInt(e -> e)
                     .toArray();

输出:[4, 3, 2, 1, 0]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-29
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    • 2014-06-28
    • 2022-10-14
    • 2019-06-25
    相关资源
    最近更新 更多