【问题标题】:Getting the result of a Lambda in java在 java 中获取 Lambda 的结果
【发布时间】:2019-03-07 16:04:03
【问题描述】:

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

我的 lambda 是:

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

而在.forEach()里面我希望能够将每个文件名依次赋给数组,例如.forEach(MyArrayList.add(this))

提前感谢您的帮助!

【问题讨论】:

    标签: java arraylist lambda java-8 java-stream


    【解决方案1】:

    使用:

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

    编辑:

    我们可以在一行中使用:

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

    【讨论】:

    【解决方案2】:

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

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

      List<Path> listA = new ArrayList<>();
      Files.newDirectoryStream(Paths.get(""), path -> path.toString().endsWith(".txt"))
           .forEach(listA::add);
      
    2. 您可以使用另一种方法,例如find,它返回一个Stream&lt;Path&gt;,这样更易​​于使用和收集列表中的元素:

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

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

    【讨论】:

    • List&lt;Path&gt; listC = Files.list(Paths.get("")).filter(p -&gt; p.toString().endsWith(".txt")).collect(Collectors.toList());
    【解决方案3】:

    您可以在forEach 中创建一个表示当前元素的变量并引用它,例如:

    ArrayList<Path> paths = new ArrayList<>();
    
    Files.newDirectoryStream(Paths.get("."), path -> path.toString().endsWith(".txt"))
            .forEach(path -> paths.add(path));
    

    也可以简化为:

    Files.newDirectoryStream(Paths.get("."), path -> path.toString().endsWith(".txt"))
            .forEach(paths::add);
    

    【讨论】:

    • 在我看来,使用方法引用 paths::add 代替 path -> paths.add(path) 会更好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    相关资源
    最近更新 更多