java 8 lambda expression for FilenameFilter -
i going through lambda expression in java 8
when changed code of thread it's working fine
new thread(new runnable() { @override public void run() { system.out.println("run"); } }).start();
is converted lambda expression as
new thread( () -> system.out.println("hello thread") ).start();
but not able convert filenamefilter expression
file file = new file("/home/text/xyz.txt"); file.list(new filenamefilter() { @override public boolean accept(file dir, string name) { name.endswith(".txt"); return false; } });
and unsuccessfully converted
file.list(new filenamefilter () { (file a1, string a2) -> { return false; } });
it's giving error in eclipse
multiple markers @ line
- syntax error, insert ";" complete statement
- syntax error, insert "}" complete block
- syntax error, insert "assignmentoperator expression" complete assignment
first things first, formatting horrible, sort out!
now, lambda syntax; convert anonymous class:
final filenamefilter filter = new filenamefilter() { @override public boolean accept(file dir, string name) { return false; } };
we start replacing anonymous class equivalent lambda single method accept(file dir, string name)
:
final filenamefilter filter = (file dir, string name) -> { return false; };
but can better, don't need define types - compiler can work out:
final filenamefilter filter = (dir, name) -> { return false; };
and can better still, method return boolean
; if have single statement evaluates boolean
can skip return
, braces:
final filenamefilter filter = (dir, name) -> false;
this can statement, example:
final filenamefilter filter = (dir, name) -> !dir.isdirectory() && name.tolowercase().endswith(".txt");
however, file
api very old, don't use it. use nio api
. has been around since java 7 in 2011 there no excuse:
final path p = paths.get("/", "home", "text", "xyz.txt"); final directorystream.filter<path> f = path -> false; try (final directorystream<path> stream = files.newdirectorystream(p, f)) { stream.foreach(system.out::println); }
and in fact example has specific method built files
takes glob:
final path p = paths.get("/", "home", "text", "xyz.txt"); try (final directorystream<path> stream = files.newdirectorystream(p, "*.txt")) { stream.foreach(system.out::println); }
or, using more modern files.list
:
final path p = paths.get("/", "home", "text", "xyz.txt"); final pathmatcher filter = p.getfilesystem().getpathmatcher("glob:*.txt"); try (final stream<path> stream = files.list(p)) { stream.filter(filter::matches) .foreach(system.out::println); }
here filter::matches
method reference because method pathmatcher.matches
can used implement functional interface predicate<path>
takes path
, returns boolean
.
as aside:
f.list(new filenamefilter() { @override public boolean accept(file dir, string name) { name.endswith(".txt"); return false; } });
this makes no sense...
Comments
Post a Comment