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!
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());
You can achieve that by collecting
the result of the newDirectoryStream
operation :
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);
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());
Or Files.list()
List<Path> listC = Files.list(Paths.get("")).filter(p -> p.toString().endsWith(".txt"))
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With