1

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
4
  • Is array the same length as arrayS? Commented Mar 10, 2017 at 21:33
  • @shmosel yeah and i have double checked it. Commented Mar 10, 2017 at 21:34
  • Java is an Object-Oriented Language. Use it. Don't use parallel arrays. Define a new class with the two values as fields, then have a single array of those objects. Now the double and the String values are always paired, so when you sort the array, all is good. Commented Mar 10, 2017 at 21:48
  • Btw, sorting stringList will also sort the underlying arrayS. If that's your intent, you can just sort it directly using Arrays.sort(). Commented Mar 10, 2017 at 21:57

1 Answer 1

3

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)]));
Sign up to request clarification or add additional context in comments.

7 Comments

@Mp.Lo. I'm not sure how you're testing, but it works fine for me: ideone.com/jYE3MC
Just a small remak: You can directly use stringList.sort(...) no need for Collections.sort(...). The code works for me too.
@shmosel I think the output is correct, but when i print the array of double it looks unsorted. But the array of strings looks sorted. hmm i dont get this.
@Mp.Lo. Why would the double array be sorted? If you want to sort it, you'll have to to so separately: Arrays.sort(array);
Cheers, the thing is that these java shortcuts although they work really nicely, they are pretty 'hard' for novice users to comprehend.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.