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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With