Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a stream of files by their size

I'm trying to get top-5 largest files in some file tree and I'm confused how to properly sort them in a stream. The thing is I have no clue where to get the parameter that my sorting should be based on.

try (Stream<Path> stream = Files.walk(Paths.get("/home/stanislav/test"))) {
    stream
        .sorted(Comparator.comparing())
        .limit(5)
        .forEach(System.out::println);
}

This is the only code chunk I could come up with. I do understand that I'm dealing with Stream of type Path. Is there any way I could transform that and do the task in a stream fashion? If so, what do I do to have my sorting line operate on the file size?

like image 311
Stanislav Codes Avatar asked Mar 07 '23 11:03

Stanislav Codes


1 Answers

Give a file length to comparator:

try (Stream<Path> stream = Files.walk(Paths.get("/home/stanislav/test"))) {
    stream
        .sorted(Comparator.comparing(p -> p.toFile().length(), Comparator.reverseOrder()))
        .limit(5)
        .forEach(System.out::println);
}

Comparator.reverseOrder() is used to sort in descending order.

like image 122
Oleksandr Pyrohov Avatar answered Mar 20 '23 05:03

Oleksandr Pyrohov