Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java sort array by the third element

i want to sort a String array descendant by it's third column in descend, the problem is that i want to sort by it's numeric value.

Example:

If i have this array initially:

String [][] array = new String[][] {
  {"Barcelona", "156", "1604"}, 
  {"Girona", "256", "97"},
  {"Tarragona", "91", "132"},
  {"Saragossa", "140", "666"}
}

I want it to become this:

{
  {"Barcelona", "156", "1604"}, 
  {"Saragossa", "140", "666"}, 
  {"Tarragona", "91", "132"}, 
  {"Girona", "256", "97"}
}

How can i do that?


1 Answers

Sort by asc:

Arrays.sort(array, Comparator.comparingInt(a -> Integer.valueOf(a[2])));

Sort by desc:

Arrays.sort(array, Comparator.comparingInt(a -> Integer.valueOf(a[2])*-1)); 
// or this
Arrays.sort(array, Comparator.comparingInt((String[] a) -> Integer.valueOf(a[2])).reversed());
like image 50
Juraj Avatar answered Jan 30 '26 01:01

Juraj