简体   繁体   English

基于双打数组排序字符串数组

[英]Sorting array of Strings based on array of Doubles

So, I want to sort descending the array of doubles, and, accordingly to sort my array of strings. 所以,我想按顺序对双精度数组进行排序,并相应地对我的字符串数组进行排序。 Both of my arrays have the same length. 我的两个数组都有相同的长度。

This is how i do it (adapted from another answer in here): 我就是这样做的(改编自这里的另一个答案):

arrayS contains the strings and array contains the doubles. arrayS包含字符串, array包含双精度数。

List<String> stringList = Arrays.asList(arrayS);
Collections.sort(stringList, Comparator.comparing(s -> array[stringList.indexOf(s)]));  

I am getting out of bounds error on the second line. 我在第二行出错了界限。

More info: 更多信息:

System.out.println("arrayS: "+arrayS.length+" array: "+array.length);

out -> arrayS: 125 array: 125

You're searching for the elements while the list/array is being sorted. 您正在对列表/数组进行排序搜索元素。 That's a recipe for disaster. 这是灾难的秘诀。 You need to use one list for index reference and another for sorting: 您需要使用一个列表作为索引引用,另一个列表用于排序:

List<String> stringList = Arrays.asList(arrayS);
List<String> indexes = new ArrayList<>(stringList);
Collections.sort(stringList, Comparator.comparingDouble(s -> array[indexes.indexOf(s)]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM