-5

How to sort a ArrayList<int[]> each element in the list is basically a tuple. So for example some elements will look like:

[5,10] [8,6] [9,5]

I want to sort the ArrayList<int[]> based the second number in the tuple. Hence the when sorted it would look like:

[9,5] [8,6] [5,10]

Jibin Balachandran
  • 3,381
  • 1
  • 24
  • 38
Ash
  • 3
  • 1

2 Answers2

0

If you are using Java 8:

list.sort(Comparator.comparingInt(i -> i[1]));
sprinter
  • 27,148
  • 6
  • 47
  • 78
0

Using Comparator

import java.util.*;

public class sorter{

 public static void main(String []args){

    List<int []> list= new ArrayList<int []>();
   //[5,10] [8,6] [9,5] 
    list.add(new int[]{5,10});
    list.add(new int[]{8,6});
    list.add(new int[]{9,5});

     for(int [] a:list){
    System.out.println(a[0]+"--"+a[1]);


    }
     System.out.println("********************");
    Collections.sort(list, new IntArrayComparator());
    for(int [] a:list){
    System.out.println(a[0]+"--"+a[1]);


    }
 }
}


class IntArrayComparator implements Comparator<int[]> {
@Override
public int compare(int[] ia1, int[] ia2) {
    int e1 = ia1[1];
    int e2 = ia2[1];;

    if (e1 > e2) {
        return 1;
    } else if (e2>e1) {
        return -1;
    } else {
        return 0;
    }
}
}
DinalP
  • 1
  • 1