简体   繁体   中英

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.

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)]));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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