Sort rows in file based upon a value on each row

Here’s an example that can solve the problem to sort rows in a file based upon a certain value on each row.
Say for example that we have a text file which has information about employees. The first value is employee nr, the second is the name of the employee and the third value is the salary.
The values on each row are separated by a comma. In this code example we are going to sort the list ascending on the salary value.

This is what the file ’employees.txt’ looks like:

In this example we use the Comparable interface to be able to do the sorting. We create a class called Person with a single field called data:

The class implements the Comparable interface, and thus must override the method compareTo (note the @Override annotation). The private method getValue is called from the compareTo method and splits the String using the dollar sign. After that it replace any commas with an empty String to be able to cast it to an integer value which is returned from the method.
This is what the main program looks like, which reads the lines from the file, creates a Person object for each line which is stored in an ArrayList.
Finally the ArrayList is sorted using the static method sort of the Collection class, and then each line is printed out to System.out.

The output of the code above will be:

Search for more Java info on this site here:
Custom Search

Please type any questions here.