Sorting a 2-Dimensional Array in Java

Recently while working for my project, I came across this situation when I had a 2-D array and I needed to sort it twice on 2 of its columns. Consider the following 2D array: [cc lang=“java”] String[][] testString = new String[][] { {“1”, “2”, “6”}, {“4”, “5”, “3”} }; [/cc] Sorting the above 2D array on zero column will give [cc lang=“java”] { {“1”, “2”, “6”}, {“4”, “5”, “3”} } [/cc] whereas sorting it on second column will give [cc lang=“java”] { {“4”, “5”, “3”}, {“1”, “2”, “6”} } [/cc] I did not want to do the most common as well as tedious thing, i.e. write my own sorting function like this: [cc lang=“java”] public void myOwnSort(String [][] exampleArray) { //code for sorting the array according to my wish. } [/cc] I wanted to avoid this for 2 resons: I would have to write the code for it ( lazy me!!). Secondly, I can possibly never match the efficiency provided by the sorting functions of java.util.Arrays

July 5, 2009 · 3 min