Can somebody explain me how to use Comparator class for sorting using Arrays.sort?
I have a 2d array.. supoose i want to sort the array 4 by 4 (let us say) using column 1 of array(let us say)...
Can somebody explain me how to use Comparator class for sorting using Arrays.sort?
I have a 2d array.. supoose i want to sort the array 4 by 4 (let us say) using column 1 of array(let us say)...
First thing to remember is that Java doesn't really have a "2D array". All arrays have a single dimension BUT any element may itself be an array (etc recursively). So what you have is an array of arrays. It sounds like you want to sort the "outer" array using the first element of each sub-array for the sort order.
You can create a comparator that compares two Objects, and in it you cast the Objects to Object[] and compare their first elements. You can then use that comparator to sort an array of arrays.
ps Is your "read CSV file" question solved?
Yeah, i could get throught the read CSV file problem... I have marked it solved...
Could you please give me an example of a code that use comparator class... ? I could better understand by that way... `
See http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/
Section 4 (Sort an Object with Comparator) shows a decent example (but read 1-3 first so it makes sense). In your case the Objects you are sorting are the "inner" arrays, so you will just want to compare their first elements (don't forget to cast them to arrays first, or you won;t be able to reference their elements).
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.