Skip to content

How to sort files in a stream by partial filename?

I use the following to sort files first by name, then by modification date:

Files.list(Paths.get(importDir))
        .map(Path::toFile)
        .sorted(Comparator.comparing(File::getName).thenComparingLong(File::lastModified))
        .forEachOrdered(file -> System.out.println(file.getName()));
                

Question: how can I refactor the File::getName part to only compare based on partial filename, like: StringUtils.substringBefore(file.getName(), "_")?

Answer

You could replace the method reference with a lambda expression on the File object, although you’ll have to specify the types (see the additional discussion here):

Files.list(Paths.get(importDir))
     .map(Path::toFile)
     .sorted(Comparator.<File, String> comparing(f -> StringUtils.substringBefore
                                                      (f.getName(), "_"))
                       .thenComparingLong(File::lastModified))
     .forEachOrdered(file -> System.out.println(file.getName()));