Reputation: 11659
I am new in functional programming in java 1.8. I have simple loop like the below code:
File folder = new File("./src/renamer/Newaudio");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
System.out.println("Here is file number: " + i);
}
I am going to change the upper for loop
to the functional format using the arrow function (like a lambda).
listOfFiles.map((file) = > {
System.out.println("Here is file number: " + i);
});
Unfortunately, it complains with:
Cannot invoke map((<no type> file) -> {}) on the array type File[]
Why i get this error? how i can resolve it?
I like to learn about Lambda, so i am not interested to the foreach
Upvotes: 2
Views: 1961
Reputation: 1210
IntStream.range(0, listOfFiles.length).forEach(file -> {
System.out.println(file);
});
Upvotes: 3
Reputation: 37414
You can use IntStream.range
to print the file numbers only
IntStream.range(0,listOfFiles.length).forEach(System.out::println);
or To print Content of array you can use
Arrays.stream(listOfFiles).forEach(System.out::println);
Compiler will convert your method reference to lambda expression at compile time so this
Arrays.stream(listOfFiles).forEach(System.out::println);
will be converted into this
=> Arrays.stream(listOfFiles).forEach(i->System.out.println(i));
With lambda you can use the expended lambda {}
as well
=> Arrays.stream(listOfFiles).forEach(i->{
if (!i.isHidden()) { // don't print hidden files
System.out.println(i);
}
});
So listFiles
returns null
is file is not a directory and for simplicity you can simply put a check at the first place
File folder = new File("./src/renamer/Newaudio");
if (folder.isDirectory()) {
File[] listOfFiles = folder.listFiles();
Arrays.stream(listOfFiles).forEach(i->System.out.println(i));
}
Reference
Lambda and Method reference concise details
Upvotes: 4
Reputation: 49656
folder.listFiles()
should be wrapped with the Optional.ofNullable
to prevent from a NullPointerException
. It can return null
if the given pathname does not denote a directory, or if an I/O error occurs.
Stream.of(ofNullable(folder.listFiles()).
orElseThrow(() -> new IllegalArgumentException("It's not a directory!")))
.forEach(f -> {});
where the forEach
method could take these arguments:
(1) an anonymous class
new Consumer<File>() {
public @Override void accept(File file) {
System.out.println(file);
}
}
(2) expended lambda expressions
(File f) -> { System.out.println(f); }
(f) -> { System.out.println(f); }
(3) simplified lambda expressions
f -> { System.out.println(f); }
f -> System.out.println(f)
(4) a method reference
System.out::println
Upvotes: 3