java


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
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
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
An array doesn't have a map method.
Stream.of(listOfFiles).forEach(file -> {
System.out.println("Here is the file: " + file);
});

Related Links

Unable to login to Rest API with spring security
Impossible to protect copyrighted file in zip file?
Connection Pool - OJDBC5 increased sessions
Loading a compiled class in Java and deserializing it's instance from a file
Can I use Dagger 2 with Java 7?
instantiate the recursively defined composite generic classes in java
Java log4j not working
PagerAdapter changed adapters content with notifying
last character not rotating correctly
Java: showInputDialog and ProcessBuilder
Concurrent read access on map structure without lock
Java Swing - Working with Threads
Using an IF statement based on a random event
JavaFX nullpointer exception when using new nodes
Why is Java's TargetDataLine.read() so slow?
Saving frequently used apps to shared preferences

Categories

HOME
gitlab
cloud
deezer
fluentd
plone
react-virtualized
q
flyway4
qore
virtualization
amazon-cloudformation
vifm
wheelnav.js
dynamics-crm-online
clearcase-ucm
django-simple-history
dosgi
windows-7-x64
solaris-10
riot.js
css-animations
zurb-foundation-6
autosys
android-widget
underflow
maxmind
libuv
perlin-noise
framemaker
hybridauth
y86
android-browser
hue
hp-ux
reportingservices-2005
nand2tetris
gpx
segment
galleria
angular-resource
appcompat
apache-fop
hendrix
kbuild
pillow
pdfclown
cudafy.net
iso8601
pintos
messenger
root-framework
savon
ctest
rvest
freelancer.com-api
rtbkit
qtableview
security-testing
0xdbe
myo
vstest.console.exe
pretty-print
streambase
javax.mail
xc16
markers
google-reader
ceil
htmlcleaner
mechanize-ruby
ivyde
ms-project-server-2010
dir
coverflow
ril
qt-faststart
type-equivalence
browser-detection
runas
datawindow
code-cleanup
yetanotherforum
calling-convention
telerik-scheduler
radcombobox
fluent-interface
.nettiers
modelstate
ti-dsp
post-build

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App