Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the result of a Lambda in java

I was wondering how to refer to the result of a lambda in Java? This is so I can store the results into an ArrayList, and then use that for whatever in the future.

The lambda I have is:

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

and inside the .forEach() I want to be able to assign each file name to the array in turn, for example, .forEach(MyArrayList.add(this))

Thanks for any help in advance!

like image 220
AristotleTheAxolotl Avatar asked Oct 02 '18 13:10

AristotleTheAxolotl


2 Answers

Use :

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

Edit :

We can achieve the same in one line using :

List<String> myPaths = Files.list(Paths.get("."))
                            .filter(p -> p.toString().endsWith(".txt"))
                            .map(Object::toString)
                            .collect(Collectors.toList());
like image 72
Nicholas Kurian Avatar answered Nov 01 '22 08:11

Nicholas Kurian


You can achieve that by collecting the result of the newDirectoryStream operation :

  1. You can add the elements in a list as you iterate it but that's not the better way :

    List<Path> listA = new ArrayList<>();
    Files.newDirectoryStream(Paths.get(""), path -> path.toString().endsWith(".txt"))
         .forEach(listA::add);
    
  2. You may use another method like find which returns a Stream<Path> that would be easier to use and collect the elements in a list :

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

    List<Path> listC = Files.list(Paths.get("")).filter(p -> p.toString().endsWith(".txt"))
                            .collect(Collectors.toList());
    
like image 38
azro Avatar answered Nov 01 '22 09:11

azro