在java中获取Lambda的结果

Ari*_*otl 7 java lambda arraylist java-8 java-stream

我想知道如何在Java中引用lambda的结果?这样我就可以将结果存储到一个中ArrayList,然后将其用于将来的任何内容.

我有的lambda是:

try {
    Files.newDirectoryStream(Paths.get("."),path -> path.toString().endsWith(".txt"))
         .forEach(System.out::println);
} catch (IOException e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

在内部,.forEach()我希望能够依次将每个文件名分配给数组,例如,.forEach(MyArrayList.add(this))

在此先感谢您的帮助!

Nic*_*s K 10

使用 :

List<String> myPaths = new ArrayList<>();
Files.newDirectoryStream(Paths.get("."), path -> path.toString().endsWith(".txt"))
     .forEach(e -> myPaths.add(e.toString()));
Run Code Online (Sandbox Code Playgroud)

编辑:

我们可以使用以下方法在同一行中实现相同:

List<String> myPaths = Files.list(Paths.get("."))
                            .filter(p -> p.toString().endsWith(".txt"))
                            .map(Object::toString)
                            .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)


azr*_*zro 9

您可以通过操作collecting的结果实现newDirectoryStream:

  1. add迭代时,您可以使用列表中的元素,但这不是更好的方法:

    List<Path> listA = new ArrayList<>();
    Files.newDirectoryStream(Paths.get(""), path -> path.toString().endsWith(".txt"))
         .forEach(listA::add);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 您可以使用其他方法find返回Stream<Path>更容易使用的方法并收集列表中的元素:

    List<Path> listB = Files.find(Paths.get(""), 1,(p, b) -> p.toString().endsWith(".txt"))
                            .collect(Collectors.toList());
    
    Run Code Online (Sandbox Code Playgroud)
  3. 要么 Files.list()

    List<Path> listC = Files.list(Paths.get("")).filter(p -> p.toString().endsWith(".txt"))
                            .collect(Collectors.toList());
    
    Run Code Online (Sandbox Code Playgroud)

  • 或者`List <Path> listC = Files.list(Paths.get("")).filter(p - > p.toString().endsWith(".txt")).collect(Collectors.toList()); ` (2认同)