1

How to map List<File> into Map<String, List<String>> without creating any additional classes using Java 8 ?

Key should be parent file name, and list should contain all children file names.

This would return Map<String, List<File>> so it doesn't compile.

Function<File, String> parentName = (f) -> f.getParent();
List<File> files = new ArrayList<>();

Map<String, List<String>> var = files
        .stream()
        .collect(Collectors.groupingBy(parentName));
2

1 Answer 1

4

You need to add a mapping downstream collector to the group by operation that maps the File Stream element into its name and collects those name into a List.

Map<String, List<String>> var = 
    files.stream()
         .collect(Collectors.groupingBy(
             File::getParent,
             Collectors.mapping(File::getName, Collectors.toList())
         ));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.