0

I've done a little java coding with some JSON values i get from the internet. I put the values into a string array, print it and look for the best (aka highest) score and it's "parent" data set. But finally it would be nice to have them sorted by this score automaticly.

The array looks like:

myArray[0][0] = "John"
myArray[0][1] = "20"       //(<- int to String)
myArray[0][2] = "21.356"   //(<- float to String)
myArray[1][0] = "Sarah"    //data
myArray[1][1] = "32"       //data
myArray[1][2] = "27.045"   //score to be sorted on

Also i thought about sorting the data-sets before putting them into the array, but as they come in plain text (by reading json values from a website), i have to make a connection of the values before sorting and this is the point, where i have to pick and put them by hand in the array at first.

Is there an efficient way to sort the array?

4
  • There are many sorting algorithms and each one serves the purpose by sorting each element. You just need to do some research what suits your requirement. Not sure what exactly your question is. Commented Apr 22, 2020 at 13:24
  • I've searched a while, but most algorithms aim on lists or 1D arrays. Others i saw aim on 2D arrays, but are only applicatable on [x][2]-arrays with exactly 2 Values (data and value to be compared). So as i tried to adapt this algorithm i failed after a few hours Commented Apr 22, 2020 at 13:27
  • 2
    stackoverflow.com/questions/15452429/java-arrays-sort-2d-array Commented Apr 22, 2020 at 13:29
  • 1
    I suggest using a different data structure than a 2-D array. I would create a class that contains members for the name, age and score. From the JSON, I would create instances of my class and add those instances to a list. I think it would be easier to sort the list than it is to sort a 2-D array. Commented Apr 22, 2020 at 13:38

2 Answers 2

1

You can create a custom comparator if you want to sort strings using the value inside them(here score) like:

Arrays.sort(myarray, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
        }
    });

Additionally you can write another comparator to sort the 2d array using a particular column.

Sign up to request clarification or add additional context in comments.

Comments

0

If I understand you correctly, you can make a stream from your array and then use something like that:

...
.sorted(Comparator.comparingDouble(Double::parseDouble))
...

Comments

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.