Splitting list by enum property to get map of enum and list

by GarciaPL on Sunday 1 July 2018

Last time I had a problem with how to split the incoming list of a type File, to get a map of list of files by FileType, which is a property of File class. The easiest way to achieve it? Reduce.

Input -> List<File> listOfFiles
Output -> Map<FileType, List<File>>

public Map<FileType, List<File>> splitFilesByFileType(List<File> listOfFiles) {
    return listOfFiles.stream()
        .reduce(new HashMap<>(), (filesByFileType, file) -> {
            FileType fileType = file.getFileType();
            if (filesByFileType.containsKey(fileType)) {
                filesByFileType.get(fileType).add(file);
            }
            else {
                filesByFileType.putIfAbsent(fileType, Lists.newArrayList(file));
            }

            return filesByFileType;
        }, (acc1, acc2) ->
        {
            acc1.putAll(acc2);
            return acc1;
        });
}