排序数组并将位置更改应用于另一个数组

时间:2015-10-07 12:29:59

标签: java arrays list sorting

我希望标题不会太误导。我有两个数组,例如:

[9, 2, 5, 6, 3]
[1.0, 7.0, 4.0, 9.0, 8.0]

首先,我想对第一个数组进行排序。然后我想将位置更改应用于第二个数组,无论第二个数组的排序是否正确。

因此应用于给定的示例,结果将是:

[2, 3, 5, 6, 9]
[7.0, 8.0, 4.0, 9.0, 1.0]

或者它也可以是List而不是数组。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

你必须跟踪指数。最简单的方法是对索引号而不是值进行排序,但是使用第一个数组的值进行比较,然后将索引的顺序应用于第二个数组。

使用Java 8,您可以按照以下方式执行此操作:

int[]    iArray={9, 2, 5, 6, 3};
double[] dArray={1.0, 7.0, 4.0, 9.0, 8.0};

double[] result=
   // original indices: ascending numbers from 0 to array length
   IntStream.range(0, iArray.length)
   // sort using the values of the first array
  .boxed().sorted(Comparator.comparingInt(ix->iArray[ix]))
   // apply to the values of the second array
  .mapToDouble(ix->dArray[ix])
   // create a result array
  .toArray();
System.out.println(Arrays.toString(result));

对于Java 8之前的解决方案,您可能会看here

答案 1 :(得分:0)

我创建一个Bean来保存两个值

public static class MyBean {
    int i;
    double d;

    // constructor
}

和比较器

static final Comparator<MyBean> COMPARATOR = new Comparator<MyBean>() {
    public int compare(MyBean b1, MyBean b2) {
       return new Integer(b1.i).compareTo(b2.i);
    }
}

然后

MyBean[] beans = {
    new MyBean(10, 2.1),
    new MyBean(20, 2.2),
    new MyBean(5, 1.3)
};
Arrays.sort(beans, COMPARATOR);
for (MyBean bean : MyBeans) {
   // do whatever
}