Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8: Map instead of simple loop

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

like image 922
Sal-laS Avatar asked Feb 22 '26 23:02

Sal-laS


1 Answers

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

like image 66
Pavneet_Singh Avatar answered Feb 24 '26 12:02

Pavneet_Singh