Posts Tagged ‘Programming’

How to Sort a Two Dimensional String Array using JAVA

February 15th, 2010 No comments

Recently I had to write a program to sort data (String) in a table and was looking for an efficient and easiest way to do sorting in java. I found two options – one was to write my own sorting program, and the other was to use the Comparator class in the Util package. I found that using Comparator or Comparable interface was very easy compared to writing my own sorting algorithm.

If you are new to using “Comparator”, I highly recommend reading this one page tutorial.

Here is a working example for sorting a two dimensional string array:

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

public class Sort {	
	public static void main(String args[]){
		//Array with address to sort
		String[][] addressArray = new String[][]{
				{"E","abc st","Sunshine", "FL"},
				{"S","abc st","Sunrise", "FL"},
				{"E","abd st","Cleveland", "OH"},
				{"N","aab st","Dallas", "TX"},
				{"W","xyz st","San Antonio", "TX"}};
		//Sort the array by city name or column 3
		Arrays.sort(addressArray, new ColumnComparator(2));
		//Print the sorted array
		for(int i=0; i<addressArray.length; i++){
			String[] row = addressArray[i];
			for(int j=0; j<row.length; j++) {
				System.out.print(row[j] + " | ");
//Class that extends Comparator
class ColumnComparator implements Comparator {
	int columnToSort;
	ColumnComparator(int columnToSort) {
		this.columnToSort = columnToSort;
	//overriding compare method
	public int compare(Object o1, Object o2) {
		String[] row1 = (String[]) o1;
		String[] row2 = (String[]) o2;
		//compare the columns to sort
		return row1[columnToSort].compareTo(row2[columnToSort]);

Results – sorted by city name

E | abd st | Cleveland | OH | 
N | aab st | Dallas | TX | 
W | xyz st | San Antonio | TX | 
S | abc st | Sunrise | FL | 
E | abc st | Sunshine | FL | 
Categories: Tech Tips Tags: , ,