Batching files and moving them using intStream

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
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

class Day015 {
    public static void main(String[] args) {
        int batchSize = 100;
        Path dirPath = getDirPath();
        final List<File> files = getFileList("/home/mohibulhasan/Downloads");
        int batchRange = (files.size() + batchSize - 1) / batchSize;

        IntStream.range(0, batchRange)
            .mapToObj(i -> files.subList(i * batchSize, Math.min(files.size(), (i + 1) * batchSize)))
            .forEach(filesInBatch -> moveToDir(filesInBatch, dirPath));
    }

    static List<File> getFileList(String path) {
        List<File> files = new ArrayList<>();
        try (Stream<Path> pathStream = Files.walk(Paths.get(path))) {
            files = pathStream
                .filter(Files::isRegularFile)
                .map(Path::toFile)
                .collect(Collectors.toList());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return files;
    }
}

The original LinkedIn graphic is preserved below.

Day 15 LinkedIn post