Using stream parallel to add id to file names.

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.io.IOException;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class Day014 {
    public static void main(String[] args) {
        Function<String, String> addIdToFile = (file) -> {
            String hashCode = Integer.toString(file.hashCode());
            return file + "-" + hashCode;
        };

        List<String> fileNames = getFileNameList("/home/mohibulhasan/Downloads");

        fileNames.stream()
            .parallel()
            .map(addIdToFile)
            .forEach(System.out::println);
    }

    public static List<String> getFileNameList(String path) {
        Function<String, String> getFileName = (file) -> {
            int index = file.lastIndexOf(".");
            if (index == -1) return "";
            return file.substring(0, index);
        };

        List<String> fileNameList = new ArrayList<>();
        try (Stream<Path> paths = Files.walk(Paths.get(path))) {
            fileNameList = paths
                .filter(Files::isRegularFile)
                .map(path1 -> path1.getFileName().toString())
                .filter(fileName -> !fileName.isEmpty())
                .map(getFileName)
                .collect(Collectors.toList());
        } catch (IOException e) {
            System.out.println("Exception Occured " + e.getMessage());
        }
        return fileNameList;
    }
}

The original LinkedIn graphic is preserved below.

Day 14 LinkedIn post