从原始arrray

时间:2016-02-24 04:08:55

标签: java arrays

我有一个包含几个double值的数组(distCent)。

double[] distCent = {0.34, 0.12, 0.01, 0.45, 0.65, 0.78};

我想获得数组中前5个最低值的索引位置(x)。我的期望输出将是这样的:

Smallest value is at position 3 with the value of 0.01
2nd smallest value is at position 2 with the value of 0.12
3rd smallest value is at position x with the value of y
4th smallest value is at position x with the value of y
5th smallest value is at position x with the value of y

为实现这一目标,我已将数组分为最低到最高,如下所示:

Arrays.sort(distCent);//use sort 
  System.out.println(Arrays.asList(distCent)); //the value in the array will be sorted

现在,我不确定如何获得前5个索引位置,以便它能产生我预期的输出或任何其他更好的方法来实现这一目标?有人可以帮忙吗?谢谢!

3 个答案:

答案 0 :(得分:2)

使用对象将数据值与索引配对。

定义Pair类,例如:

public class Pair implements Comparable<Pair> {
    double value;
    int index;

    public Pair(double v, int i) {
        value = v;
        index = i;
    }
    public int compareTo(Pair p) {
        if (value - p.value < 0) return -1;
        if (value - p.value > 0) return 1;
        return 0;
}

然后创建你的数组。

Pair[] distCent = {new Pair(0.34, 0), new Pair(....)};

现在,排序后,当您访问数组时,您可以看到索引。

distCent[i].index //this is the original index of the item

我建议使用自定义打印方法而不是asList方法,因为它提供了更大的灵活性。您可以使用自定义方法打印索引。

答案 1 :(得分:2)

试试这个。

double[] distCent = {0.34, 0.12, 0.01, 0.45, 0.65, 0.78};
String[] names = {"Smallest", "2nd smallest", "3rd smallest", "4th smallest", "5th smallest"};
int[] c = {0};
IntStream.range(0, distCent.length)
    .mapToObj(n -> new double[]{n, distCent[n]})
    .sorted(Comparator.comparing(a -> a[1]))
    .limit(names.length)
    .forEach(a -> System.out.printf("%s value is at position %d with the value of %.2f%n",
        names[c[0]++], (int)a[0] + 1, a[1]));

输出

Smallest value is at position 3 with the value of 0.01
2nd smallest value is at position 2 with the value of 0.12
3rd smallest value is at position 1 with the value of 0.34
4th smallest value is at position 4 with the value of 0.45
5th smallest value is at position 5 with the value of 0.65

答案 2 :(得分:0)

import java.util.ArrayList;
...
ArrayList<double> temp = new ArrayList<double>();
for(double i : distCent){
    temp.add(i);
}
Arrays.sort(distCent);
for(int x = 0; x < 5; x++){
    //index is the original location
    int index = temp.indexOf(distCent[x]);
}

要保留原始索引,您需要创建原始数组的副本,然后根据已排序的数组检查值。 Java中的列表有一个方便的indexOf方法来执行此操作。