2

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?

Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61
  • 2
    Perhaps draw inspiration from http://stackoverflow.com/questions/5805602/how-to-sort-list-of-objects-by-some-property – Eli Sadoff Jan 11 '17 at 21:40
  • 1
    `Arrays.sort(array, Comparator.comparingInt((String[] a) -> Integer.parseInt(a[2])).reversed());` – shmosel Jan 11 '17 at 21:42

2 Answers2

5

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());
Juraj
  • 738
  • 2
  • 9
  • 26
4

You can implement a custom Comparator<String[]> to perform your comparisons. Something like,

String[][] array = new String[][] { { "Barcelona", "156", "1604" }, 
        { "Girona", "256", "97" }, { "Tarragona", "91", "132" }, 
        { "Saragossa", "140", "666" } };
Arrays.sort(array, new Comparator<String[]>() {
    @Override
    public int compare(String[] o1, String[] o2) {
        return Integer.valueOf(o2[2]).compareTo(Integer.valueOf(o1[2]));
    }
});
System.out.println(Arrays.deepToString(array));

Which outputs (as requested)

[[Barcelona, 156, 1604], [Saragossa, 140, 666], [Tarragona, 91, 132], [Girona, 256, 97]]

See also, Object Ordering - The Java Tutorials (and especially the subsection "Writing Your Own Comparable Types") for more.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • The problem is that i don't know how to use Comparator, any good guide or video? –  Jan 11 '17 at 23:20