-3

I want to search for all .po files in a directory and add them to a HashMap.

My directories looks like the following:

dir1\<any number of subdirs>\*_en_*.po
                             *_it_*.po
                             ...
dir2\<any number of subdirs>\*_en_*.po
.                            *_es_*.po
.                            ...
.
dirn\<any number of subdirs>\...

How can I represent/search these files with the help of java-Streams and HashMap<String, List<File>>, with en/de/it.po as a List<File> type and the respective directory root of these files dir1\subdir-1\**\subdir-n as a key?

I've tried the following solution from a similar post: https://stackoverflow.com/a/62824848/10042081 but I wasn't able to manipulate the filter/groupings correctly in order to solve my problem.
I've also tried to use listFiles() + isDirectory() recursively in order to achieve the desired result, with no success.

Doesbaddel
  • 214
  • 3
  • 17
  • 3
    You may want to show your attempt code, and tell the details about the problems that you are having with it – Hovercraft Full Of Eels Jul 24 '22 at 22:24
  • Thanks for your answer. I've used the mentioned solution in the other post and tried to add/replace the filter with `.filter(p -> p.toString().endsWith("po")` which didn't work, because nested directories were not included. I didn't knew what I needed to change in order to get the desired result. – Doesbaddel Jul 25 '22 at 06:42

1 Answers1

2

This is pretty simple using Files.find() to walk a directory tree looking for matching files, and Collectors.groupingBy() to convert that stream into the desired map.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Demo {
    public static void main(String[] args) {
        for (String dir : args) {
            try (var files = Files.find(Path.of(dir), 256,
                                        (p, attr) -> p.getFileName().toString().endsWith(".po"))) {
                Map<String, List<Path>> po_files =
                    files.collect(Collectors.groupingBy(p -> p.getParent().toString()));
                System.out.println(po_files);
            } catch (IOException e) {
                System.err.println(e);
                System.exit(1);
            }
        }
    }
}

This will give you a map where the keys are paths to directories, and the values are lists of paths to all the .po files in those directories.

Shawn
  • 47,241
  • 3
  • 26
  • 60