2

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(), "_")?

membersound
  • 81,582
  • 193
  • 585
  • 1,120

1 Answers1

1

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()));
Mureinik
  • 297,002
  • 52
  • 306
  • 350