Java 8将多个文件平面映射到行

del*_*lpo 2 java-8 java-stream

给定一组文件名:

bigList = Arrays.stream(files)
    .flatMap(file - > {
        try {
            return Files.lines(Paths.get(path + SEPARATOR + file));
        } catch (IOException e) {
            LOGGER.log(Level.WARNING, "No se puede encontrar el archivo " + file);
        }
        return null;
    })
    .filter(str - > str.startsWith("ABC"))
    .distinct()
    .map(Mapper::mapToObj)
    .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

当我使用传统的for循环时(而不是Arrays.stream(..).flatMap(..)),这会返回不同的输出

for (String file: files) {
    bigList.addAll(Files.lines(Paths.get(path + SEPARATOR + file))
        .filter(str - > str.startsWith("ABC"))
        .distinct()
        .map(Mapper::mapToObj)
        .collect(Collectors.toList()));
}
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

提前致谢

干杯

Öme*_*den 6

这是因为呼吁distinct().

当您调用时flatmap,它会将所有文件中的所有行组合成一个Stream<String>,因此distinct()将返回所有文件中不同的行.

当您使用for循环时,您只是distinct()单独调用每个文件中的行.因此,当您将它们添加到列表中时,如果不同文件中存在相同的行,则仍可能存在重复项.

  • 欢迎你,顺便感谢编辑@Andrew Mairose. (3认同)