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

jpa(hibernate) one-to-many flush is not flushing the many side collection
404 when creating Web Service with eclipse
Adding a GPS receiver to java code?
Dynamic class loading vs injection
Populate attribute in List of Objects in Java using Lambda
Asynchronous service with Spring boot
No protocol malformed URL Exception thrown at me when trying to parse an XML String
Read 3 selected item in the same time
how to use setter and getter in different functions?
Unable to download file from Google Drive using Java API
Sending and reading a 2D array using sockets Java
/Date(long + 1000)/ format
possible paths to the top of a staircase
What is the best way to implement search in Android?
What is <?> in java? [duplicate]
XML file in a Linux environment not showing the correct symbol

Categories

HOME
log4j
client
wso2
listview
google-play
platform-builder
objectgears
sd-card
rsyslog
jsp-tags
jpeg
pivotal-cloud-foundry
node-notifier
dacpac
windows-10-universal
dax
export-to-csv
zend-framework3
moonmail
size
designer
quartz-scheduler
facebook-page
footer
flux
text-rendering
openedx
dbext
cx-freeze
orleans
accessor
pass-by-reference
dxf
rundeck
crystal-reports-2010
cas
applozic
libuv
newline
stormpath
.net-4.0
fog
nssegmentedcontrol
overlap
space-complexity
espeak
android-browser
objectlistview
reportbuilder
ansible-playbook
greenrobot-eventbus
tasker
avro4s
ruby-on-rails-3.1
texmaker
unixodbc
http-redirect
s
.net-4.6.2
slick-3.0
thin
babel-core
hibernate-tools
kbuild
spring-cache
sonarlint-vs
database-optimization
thrust
transmitfile
gridview-sorting
bluemix-app-scan
historian
cartesian-product
icu4j
metaclass
kcachegrind
wyam
rgeo
0xdbe
ios9.1
proj4js
geonetwork
sorl-thumbnail
offloading
qpainter
knuth
codeigniter-routing
preferences
eol
sgen
wp-query
resty-gwt
cloud-connect
mcts
floating-point-precision
inbox
django-nonrel
drools-planner
android-hardware
typoscript2
libstdc++
code-cleanup
hgsubversion
bigcouch
appendto
web-application-design
exchange-server-2003
pascal-fc
text-coloring
project-hosting
gacutil
spec#
grid-system
rtml

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App