Spiga

How To Sort a File On the basis of the column Using Java

How To Sort a File On the basis of the column Using Java

Java Program to sort the file.
In the earlier post we have seen how to sort the CSV file. Now, we will see the generalised java code to sort the file on the basis of particular column. This code can be used for any type of files, like csv, txt etc. This can be useful to sort the big files on the basis of the column. For using this code, we need to take care of few things:
The format of the file should be like in this format:
The header or the column should be there and should be the first line of the file, else we will missed the first line.
Header/Col1: Header/Col2 : Header/Col3
a : c : e
s : a  : d
.. : .. : ...
Algorithm Used:
It’s not the rocket science, we have keep it simple and have used the simple algorithm. The each row has been considered as one java object. The column on which we have to sort is taken as the key and against this key we have the associated row data java objects as values. We sort the key and display the respective values.
For example: If we have to sort the above file on column 2, we will create two java objects which will have values:
Java@Obj1: a,c,e
Java@Obj2: s,a,d

Now, we are sorting on column 2, so for first row, key will be c and c will be mapped with the value Java@Obj1: a,c,e and for the second row: key will be a and a will be mapped with the value Java@Obj2: s,a,d. Now we will sort the keys, i.e. c and a and then we will display the mapped value for the sorted keys.

Here is the Java Class Example: