-2

I am looking to sort an array of high scores, stored in a 2d array structured like this:

[name 1][score 1]
[name 2][score 2]
[name 3][score 3]
[name 4][score 4]
[name 5][score 5]
[name 6][score 6]

So if the array looks like this:

[name 1][100]
[name 2][200]
[name 3][50]
[name 4][700]
[name 5][640]
[name 6][277]

I would like it to be sorted like this:

[name 4][700]
[name 5][640]
[name 6][277]
[name 2][200]
[name 1][100]
[name 3][50]

So I basically has to sort the rows according to the highest int stored in the row.

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
  • 4
    Okay so we see the input and the expected output, but where is your code or what you've tried so far?? – Zach_Mose Jan 13 '21 at 10:49
  • 1
    Add your code or the error you are facing brother... If you have any idea of hashing or key-value pair ... this won't be much problematic for you – Sumit Singh Jan 13 '21 at 10:51
  • 1
    Does this answer your question? [java Arrays.sort 2d array](https://stackoverflow.com/questions/15452429/java-arrays-sort-2d-array) [how to display in descending order a two dimensional array](https://stackoverflow.com/questions/26748842/how-to-display-in-descending-order-a-two-dimensional-array) – Nowhere Man Jan 13 '21 at 11:03
  • `Arrays.sort(yourArray, Comparator.comparingInt(i -> i[0]))` – Lino Jan 13 '21 at 11:05
  • Additionally, you should probably **not** use arrays for this. But a `Collection` of your own `class` – Lino Jan 13 '21 at 11:06
  • If the input array is 2D array of objects, it can be sorted as: `Arrays.sort(data, Comparator.comparingInt(r -> ((Integer)r[1])).reversed().thenComparing(r -> ((String)r[0])));` – Nowhere Man Jan 13 '21 at 11:30

1 Answers1

0
public static void main(String[] args) {
    Object[][] array= {
            {"Name 1", 100},
            {"Name 2", 200},
            {"Name 3", 50},
            {"Name 4", 700} 
            };

    Arrays.sort(array, new java.util.Comparator<Object[]>() {
        public int compare(Object[] a, Object[] b) {
            int result = Integer.compare((Integer)b[1], (Integer)a[1]);
            if(result==0) { //Incase the scores are same, sort by name
                return ((String)a[0]).compareTo((String)b[0]);
            }
            return result;
        }
    });
    
    for (Object[] row : array) {
        for (Object x : row) { 
            System.out.print(x + " "); 
        }
        System.out.println();
    }   
}

Name 4   700   
Name 2   200   
Name 1   100   
Name 3   50  
Amit Kumar Lal
  • 5,537
  • 3
  • 19
  • 37