Using Collectors.groupingBy and Collectors.counting to get numbers of file present of a particular type
Transcribed from the original LinkedIn image post.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
| import java.io.IOException;
import java.nio.file.*;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class Scratch {
public static void main(String[] args) throws IOException, InterruptedException {
Function<String, String> fileNameRemove = (fileName) -> {
int index = fileName.lastIndexOf(".");
if (index == -1) return "";
return fileName.substring(index);
};
try (Stream<Path> paths = Files.walk(Paths.get("/home/mohibulhasan/Downloads"))) {
Map<String, Long> fileCountByType = paths
.filter(path -> Files.isRegularFile(path))
.map(path -> path.getFileName().toString())
.filter(fileName -> !fileName.isEmpty())
.map(fileNameRemove)
.collect(Collectors.groupingBy(
Function.identity(), Collectors.counting()
));
System.out.println(fileCountByType);
}
}
}
|
The original LinkedIn graphic is preserved below.
