-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]

3
  • 4
    Why did you tag java and python for this? And more importantly, show your code attempt for this. StackOverflow is not a code writing service. Commented Nov 2, 2016 at 4:39
  • Which value do you want it sorted on? Index 0 or index 1? Commented Nov 2, 2016 at 4:41
  • Check this one out stackoverflow.com/questions/4699807/… Commented Nov 2, 2016 at 5:18

2 Answers 2

0

If you are using Java 8:

list.sort(Comparator.comparingInt(i -> i[1]));
Sign up to request clarification or add additional context in comments.

Comments

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;
    }
}
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.