2016-09-20 50 views
2

爪哇8流的多个文件flatmap到给定文件名的阵列线

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()); 

这被返回时我使用一个传统的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())); 
    } 

为什么会发生这种情况?

在此先感谢

干杯

+0

样本输入和输出? –

+0

@BoristheSpider你说得对,我修好了。 – delpo

+4

它返回不同的输出,还是以不同的顺序输出相同的输出? –

回答

6

这是因为调用distinct()的。

当您拨打flatmap时,它将所有文件中的所有行合并为一个Stream<String>,因此distinct()将返回所有文件中不同的行。

当您使用for循环时,您只能分别在每个文件的行上调用distinct()。所以,当你将它们添加到你的列表中时,如果同一行存在于不同的文件中,仍然可能有重复。

+0

这就是问题所在。谢谢。 – delpo

+3

不客气,顺便说一句,谢谢编辑@Andrew Mairose。 –