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?

2
  • 2
    Perhaps draw inspiration from stackoverflow.com/questions/5805602/… Commented Jan 11, 2017 at 21:40
  • 1
    Arrays.sort(array, Comparator.comparingInt((String[] a) -> Integer.parseInt(a[2])).reversed()); Commented Jan 11, 2017 at 21:42

2 Answers 2

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());
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

The problem is that i don't know how to use Comparator, any good guide or video?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.