在Java中获取Lambda的结果

时间:2018-10-02 13:54:25

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

我想知道如何在Java中引用lambda的结果?这样一来,我可以将结果存储到{ "InventoryID": {"value": "AACOMPUT01"}, "Attributes": [ { "AttributeID": {"value": "Color"}, "Value": {"value": "Black"} }, { "AttributeID": {"value": "Configurable Attributes"}, "Value": {"value": "Test"} } ] } 中,然后将其用于将来的任何事情。

我拥有的lambda是:

ArrayList

try { Files.newDirectoryStream(Paths.get("."),path -> path.toString().endsWith(".txt")) .forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); } 内,我希望能够依次将每个文件名分配给数组,例如.forEach()

感谢您的任何帮助!

3 个答案:

答案 0 :(得分:10)

使用:

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

答案 1 :(得分:9)

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

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

    add
  2. 您可以使用List<Path> listA = new ArrayList<>(); Files.newDirectoryStream(Paths.get(""), path -> path.toString().endsWith(".txt")) .forEach(listA::add); 之类的另一种方法,该方法返回find,该方法将更易于使用并收集列表中的元素:

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

    Files.list()

答案 2 :(得分: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);