sarth sachdeva
sarth sachdeva

Reputation: 11

sorting an array list of int arrays in terms of the first and the second element of the int arrays

ArrayList<int[]> segment = new Arraylist<int[]>();
segment.add(new int[]{2,3,1});
segment.add(new int[]{2,1,1});
segment.add(new int[]{1,1,1});
segment.add(new int[]{2,4,1});
segment.add(new int[]{3,3,1});

What I want to do is sort this ArrayLists according to the first element of each array and if the element is same do the sorting according to the 2nd element of the array/arrays

For instance the above lines of code should be modified to, (1,1,1) (2,1,1) (2,3,1) (2,4,1) (3,3,1)

this is what i have so far in temrs of solving this,

    public static void SortSegment(ArrayList<int[]> segment){
        Collections.sort(segment, new Comparator<int[]>() {
             public int compare(int[] a, int[] b) {
                  return (a[0] - b[0]);
             }
        });
    }

this piece of code sorts the arraylist of int arrays according to the first element of each of the int arrays. How do i modify it to work for cases where the first element is the same so it takes into consideration the 2nd element?

thanks.

Upvotes: 1

Views: 2561

Answers (3)

Dev. Joel
Dev. Joel

Reputation: 1147

try this

if(a[0] - b[0]==0) //Like the first row of the matrix if so, we proceed to the next to know which is lower

code complete

Collections.sort(segment, new Comparator<int[]>() {
         public int compare(int[] a, int[] b) {
              if(a[0] - b[0]==0) //if equals
              {
                  return a[1]-b[1];//recompare 
              }
              else
                  return a[0]-b[0];
         }
    });

Upvotes: 2

Bohemian
Bohemian

Reputation: 425428

Try this:

segments.sort(Comparator.comparingInt(a -> a[0])
    .thenComparing(a -> a[1])
    .thenComparing(a -> a[2]));

Upvotes: 0

sprinter
sprinter

Reputation: 27996

The Comparator interface has some useful utility (default) methods in Java 8 that are useful for custom sorting:

segment.sort(Comparator.comparingInt(el -> el[0]).thenComparingInt(el -> el[1]));

Upvotes: 1

Related Questions