user7274818
user7274818

Reputation:

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?

Upvotes: 2

Views: 461

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201447

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.

Upvotes: 4

Juraj
Juraj

Reputation: 778

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());

Upvotes: 5

Related Questions