[Solved] How to sort numeric value in file


To read a file of “lines” in Java you can use the Files class like this:

final List<String> l = 
        Files.readAllLines(Paths.get("/some/path/input.txt"));

This reads a file and stores each line in a List. When you have the List of String objects you can use a simple Comparator and the Collections.sortmethod. Check this code out:

final List<String> l = Arrays.asList(
        "id1 0.44 0.5 #0.13800099498102508",
        "id2 0.44 0.8 #0.22080159196964014",
        "id3 0.44 0.5 #0.15771581712401433",
        "id4 0.44 0.8 #0.22080159196964014",
        "id5 0.11 0.5 #0.04353560295326771",
        "id6 0.11 0.2 #0.017414241181307084");

Collections.sort(l, new Comparator<String>() {
    @Override
    public int compare(final String o1, final String o2) {
        return o1.substring(o1.indexOf("#") + 1).compareTo(o2.substring(o2.indexOf("#") + 1));
    }
}.reversed());

l.forEach(System.out::println);

The output is:

id2 0.44 0.8 #0.22080159196964014
id4 0.44 0.8 #0.22080159196964014
id3 0.44 0.5 #0.15771581712401433
id1 0.44 0.5 #0.13800099498102508
id5 0.11 0.5 #0.04353560295326771
id6 0.11 0.2 #0.017414241181307084

The JavaDocs for Comparator can be found here.

Note that this solution uses some Java 8 features. If pre Java 8 is used the following comparator can be used instead (notice the - sign):

Comparator<String> c = new Comparator<String>() {
    @Override
    public int compare(final String o1, final String o2) {
        return -o1.substring(o1.indexOf("#") + 1).compareTo(o2.substring(o2.indexOf("#") + 1));
    }
};

Another alternative is to use Java 8 Streams. You can combine it with the new Comparator.comparing method like this:

final List<String> sorted = l.stream()
        .sorted(
                Comparator.<String, String>comparing(
                        (str) -> str.substring(str.indexOf("#")))
                        .reversed())
        .collect(Collectors.toList());

Note that this does not sort the original List but creates a new sorted List.

Finally, to save the output to a file again the Files class comes to the rescue:

Files.write(
        Paths.get("/some/path/output.txt"),
        sorted);

You can use the write method to write out any Iterable object such as the List that you just sorted.

2

solved How to sort numeric value in file