0

I have a folder main with many sub folders like this

1
2
4
7
10

I would like to get the ID of the last folder in the collection. In this case folder "10". How can I do this in Java 8?

isADon
  • 3,433
  • 11
  • 35
  • 49
  • What do you mean with `last folder`? The one which in natural order is the last or the one which was last time modified (there might be differences based on the OS when the directory timestamp is updated). – SubOptimal Oct 16 '17 at 11:33
  • Or the most recently created? Or the one with the highest value when the names are interpreted as numbers? Or not interpreted as numbers? – user207421 Oct 16 '17 at 11:37
  • "the one with the highest value when the names are interpreted as numbers" That one – isADon Oct 16 '17 at 11:54
  • If you have the directories in a `List` you could use [Collections.sort(list, comparator)](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#sort-java.util.List-java.util.Comparator-) to sort them in the way you want. What have you tried so far? – SubOptimal Oct 16 '17 at 13:09

1 Answers1

0

You can sort folders by last modified date like:

public static String lastFolder() throws IOException {

        Stream<Path> dirList = Files.list(Paths.get("your_directoy_ath")).sorted(new Comparator<Path>() {
            @Override
            public int compare(Path path1, Path path2) {
                Long file1Name = path1.toFile().lastModified();
                Long file2Name = path2.toFile().lastModified();
                return file2Name.compareTo(file1Name);

            }
        });

        return dirList.collect(Collectors.toList()).get(0).getFileName().toString();
    }

You can modify sorting method as per your need, if you need by name..can do that too

Yogi
  • 1,805
  • 13
  • 24