Site icon codippa

How to sort a two-dimensional array on column values in java / How to sort a two-dimensional array in java

Sorting means arranging elements in a specific order. Order can be of two types : ascending and descending.

  • Ascending order is when the elements are arranged in order of increasing value(smaller to larger).
  • Descending order implies the elements are arranged in order of decreasing value(or larger to smaller values).

Sorting a one dimensional array in java is straight forward and easy, just call java.util.Arrays.sort with the array to sort as argument and you get the array sorted. But what if you want to sort a two dimensional array. There is no direct method to sort a two dimensional array in java. Just pause and think, you will surely need to think on the approach when you encounter this task for the first time.

Approach
For sorting a two dimensional array, first you need to decide on which column you have to sort or to phrase it correctly, on which array index you need to sort since a 2d array in java is an array of arrays. A 2d array in java can be visualized as :

 Illustration 1. Two-dimensional array representation in java

Above array when sorted on index 0, will look like

            Illustration 2. Array sorted on first element

Sorting on index 0 means that first elements of all the arrays will be compared and sorted. In terms of conventional arrays, this means that the first column elements are sorted.

Similarly, sorting on index 1 means that second elements of all the arrays will be compared and sorted. In terms of conventional arrays, this means that the elements of second column are sorted.

Finally you need to decide whether to sort elements in ascending order or descending order.

For more details on 2d array, visit How is a two dimensional array represented in java

Implementation
Since there is no straight method available in java to sort a two dimensional array, we need to develop our own implementation.
If you have noticed, there is an overloaded sort method in java.util.Arrays class which takes two arguments : the array to sort and a java.util.Comparator object.
If we pass in our own custom Comparator, it would sort the array as we require. Let’s see how.

import java.util.Arrays;
import java.util.Comparator;

public class PartNumberQuantityDetailer {
    // initialize a two dimensional array
    static Integer[][] itemIdAndQty = new Integer[5][2];

    public static void main(String[] args) {
	// initialize array values
	itemIdAndQty[0][0] = 1234;
	itemIdAndQty[0][1] = 46;
	itemIdAndQty[1][0] = 5443;
	itemIdAndQty[1][1] = 564;
	itemIdAndQty[2][0] = 362;
	itemIdAndQty[2][1] = 24;
	itemIdAndQty[3][0] = 6742;
	itemIdAndQty[3][1] = 825;
	itemIdAndQty[4][0] = 347;
	itemIdAndQty[4][1] = 549;
	System.out.println("Before sorting");
	// show the contents of array
	displayArray();
	// sort the array on item id(first column)
	Arrays.sort(itemIdAndQty, new Comparator() {
	   	@Override
                //arguments to this method represent the arrays to be sorted   
		public int compare(Integer[] o1, Integer[] o2) {
                    //get the item ids which are at index 0 of the array
	            Integer itemIdOne = o1[0];
	            Integer itemIdTwo = o2[0];
		    // sort on item id
		    return itemIdOne.compareTo(itemIdTwo);
		}
	});
	// display array after sort
	System.out.println("After sorting on item id in ascending order");
	displayArray();
	// sort array on quantity(second column)
	Arrays.sort(itemIdAndQty, new Comparator() {
		@Override
		public int compare(Integer[] o1, Integer[] o2) {
	            Integer quantityOne = o1[1];
		    Integer quantityTwo = o2[1];
		    // reverse sort on quantity
		    return quantityOne.compareTo(quantityTwo);
		}
	});
	// display array after sort
	System.out.println("After sorting on quantity in ascending order");
	displayArray();

    }

    private static void displayArray() {
	System.out.println("-------------------------------------");
	System.out.println("Item id\t\tQuantity");
	for (int i = 0; i < itemIdAndQty.length; i++) {
		Integer[] itemRecord = itemIdAndQty[i];
		System.out.println(itemRecord[0] + "\t\t" + itemRecord[1]);
	}
	System.out.println("-------------------------------------");
    }
}

Output

 

Before sorting
————————————-
Item id        Quantity
1234           46
5443           564
362             24
6742           825
347             549
————————————-
After sorting on item id in ascending order
————————————-
Item id        Quantity
347              549
362              24
1234            46
5443            564
6742            825
————————————-
After sorting on quantity in ascending order
————————————-
Item id        Quantity
362              24
1234            46
347              549
5443            564
6742            825
————————————-

 

Explanation
A two dimensional array is created and initialized with default values. First column of the array consists of item id and second column is its quantity.
First the array is sorted on item ids(first column) and then on its quantity(second column). For sorting the array, sort method of java.util.Arrays is used which takes 2 arguments : the array to be sorted and a java.util.Comparator object.
We pass an anonymous Comparator object(anonymous object means an object which has no name and which is created at its place of use only).
As explained earlier and can be seen from Illustration 1, a 2d array in java is an array of arrays, thus, for sorting a 2d array on a column, we have to sort an integer array, therefore the generic type of this Comparator object should be Integer[ ].
Inside Comparator object, we implement its compare method which takes two objects of Integer[ ] type. These Integer objects represent the arrays to be compared.
Since we need to compare values of first column(item ids), we retrieve the values at index 0 of the supplied Integer[ ] objects and compare them using compareTo method.
Similarly, for sorting the array on second column(quantity), the values at index 1 of the Integer[ ] objects are retrieved and compared.
Result of sorting on both columns can be seen from the output of the above program.

Let’s tweak in

  1. In place of using an anonymous Comparator object, a separate class which implements java.util.Comparator interface and implements its compare method can be used. In that case, instead of passing the definition of Comparator in the above program, an object of this class will be supplied.
  2. The above program can also be used to sort the array on column values in descending order. Just swap the caller and argument of compare method.
  3. The above method can also be used to sort an array of types double, String, float etc. You only need to change the generic type of Comparator according to the type of array.
Hope this article made you learn something new or helped you out. Click the clap below to show your appreciation.
Exit mobile version