Home > other >  Easy sort list 2D by column
Easy sort list 2D by column

Time:03-11

I'm quiet new in Java data manipulation so I need some help if someone have a some good tips. Actually, I want just to find a easy way to sort a 2D list.

I create a list like this:

List<int[]> A = new ArrayList<int[]>();
A.add(new int[] {0,1});
A.add(new int[] {5,40});
A.add(new int[] {7,5});

And then I want to have a result sorted by the second element like:

0 -> 1
7 -> 5
5 -> 40.

I tried something like Arrays.sort(A.toArray(), (int[]a, int[]b) -> a[0] - b[0]); but it doesn't work.

Is there a simple solution to do that sort list?

CodePudding user response:

Try this:

List<Integer[]> A = new ArrayList<>();
A.add(new Integer[] {0,1});
A.add(new Integer[] {5,40});
A.add(new Integer[] {7,5});
    
A.sort(Comparator.comparingInt(a -> a[1]));
    
for (Integer[] a : A) {
    System.out.println(Arrays.toString(a));
}

CodePudding user response:

You can simply do:

list.sort(Comparator.comparingInt(arr -> arr[1]));

or you can also do:

Collections.sort(list, Comparator.comparingInt(arr -> arr[1]));

If you want to sort into a new List<int[]> you can use stream:

List<int[]> listSorted = list.stream()
        .sorted(Comparator.comparingInt(arr -> arr[1]))
        .toList();

CodePudding user response:

    for (int i = 0; i < A.size(); i  ) {
        int[] temp = A.get(i);
        for (int j = i   1; j < A.size(); j  ) {
            int[] temp2 = A.get(j);
            if (temp[1] > temp2[1]) {
                A.set(i, temp2);
                A.set(j, temp);
            }
        }
    }
  • Related