stringsortingjava-8java-streamfile-read

Comparing and thenComparingInt not working within the same string


I'm trying to get some .txt files , reading them in order and then writing their content( with some logic) into an excel sheet. The files are named like this:

FileB_60.txt
FileB_90.txt
FileB_120.txt

fileA_60.txt
fileA_90.txt
fileA_120.txt

In the end, I want them to be read just like that, ordered by name and number. If I don't use any sorting step, they're read randomly.

String fileExtension = ".txt";
    try (Stream<Path> paths = Files.walk(Paths.get(resourcesPath))) {
                Comparator<Path> byName = Comparator.comparing(p -> p.getFileName().toString());
                Comparator<Path> byNameAndNumber = byName.thenComparingInt(p -> Integer.parseInt(p.getFileName().toString().split("_")[1].replace(fileExtension, "")));
                for (Path eachFilePath : paths
                        .filter(p -> p.getFileName().toString().endsWith(fileExtension))
                        .sorted(byNameAndNumber)
                        .collect(Collectors.toList()))
    ...

This way, they're read like:

FileB_120.txt
FileB_60.txt
FileB_90.txt

fileA_120.txt
fileA_60.txt
fileA_90.txt

So it seems like it's ordering only by the name (capital letter first) I was wondering if I'm doing something wrong here, since I'm sorting within the same string


Solution

  • One important thing about thenComparing... methods: the comparator injected is only used when the initial comparator (called byName in your example) considers the 2 elements are equal, which is never the case in your example.

    The comparator byName must compare only the first part of the file name (the one before the _).

    Comparator<Path> byName = Comparator.comparing(
        p -> p.getFileName().toString().split("_")[0]);