Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading