Prachi
Prachi

Reputation: 554

Java: How to extract the largest name from multiple folders kept at a path into a variable where folder names are all numeric?

There is a directory which has many folders. The folder names are all numeric. How to extract the folder name which has the greatest value into an integer variable in java?

For example: Lets say directory .../home/user has following folders:

.../home/user/19620918

.../home/user/19620919

.../home/user/19620920

How to get x = 19620920, where x is lets say the integer variable, using the simplest and most efficient code?

Upvotes: 0

Views: 56

Answers (1)

Glains
Glains

Reputation: 2863

Using a Files.list(), you can use the following approach:

public static OptionalInt getMaxNumericFilename(Path path) {
    try (Stream<Path> files = Files.list(path)) {
        return files
            .filter(Files::isDirectory)
            .map(Path::getFileName)
            .map(Path::toString)
            .mapToInt(Integer::parseInt)
            .max();
    } catch (IOException e) {
        return OptionalInt.empty();
    }
}

Example usage:

Path path = Path.of(".../home/user");

OptionalInt max = getMaxNumericFilename(path);
System.out.println(max.getAsInt());

If the OptionalInt is empty, there are no present directories. If you want to add additional resiliency, you can filter if the filename is an int before parsing with Integer::parseInt which can throw an exception.

This solution will work for filename numbers up to Integer.MAX_VALUE (2.147.483.647). Consider using long or BigDecimal if required.

Upvotes: 3

Related Questions