gpt4 book ai didi

java - 从原数组中获取排序后数组的索引位置

转载 作者:行者123 更新时间:2023-11-30 06:55:11 24 4
gpt4 key购买 nike

我有一个包含多个 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 个索引位置,以便它产生我预期的输出或任何其他更好的方法来实现它?任何人都可以帮忙吗?谢谢!

最佳答案

试试这个。

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

关于java - 从原数组中获取排序后数组的索引位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35593072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com