I am going through the lambda expression in java 8
when i changed the code of thread it's working fine
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("run");
}
}).start();
is converted to lambda expression as
new Thread(
() -> System.out.println("Hello from thread")
).start();
But i am not able to convert the 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 to this as
file.list(new FilenameFilter () {
(File a1, String a2) -> {
return false;
}
});
it's giving error as in eclipse as
Multiple markers at this line
- Syntax error, insert ";" to complete Statement
- Syntax error, insert "}" to complete Block
- Syntax error, insert "AssignmentOperator Expression" to complete Assignment
FileNameFilter
is a functional interface. You don't need to instantiate it explicitly.Note also, that
f
should be a directory, not a file as in your example. Your example wheref1
is a file will returnnull
with the specified filter.First things first, your formatting is horrible, sort it out!
Now, lambda syntax; to convert the anonymous class:
We start by replacing the anonymous class with an equivalent lambda for the single method
accept(File dir, String name)
:But we can do better, we don't need to define the types - the compiler can work those out:
And we can do better still, as the method return a
boolean
; if we have a single statement that evaluates to aboolean
we can skip thereturn
and the braces:This can be any statement, for example:
However, the
File
API is very old, so don't use it. Use thenio API
. This has been around since Java 7 in 2011 so there is really no excuse:And in fact your example has a specific method built into
Files
that takes a Glob:Or, using the more modern
Files.list
:Here
filter::matches
is a method reference because the methodPathMatcher.matches
can be used to implement the functional interfacePredicate<Path>
as it takes aPath
and returns aboolean
.As an aside:
This makes no sense...
It should be simpler :
or even :
The lambda expression replaces the instantiation of the abstract class instance.
You don't have to put the class name, if you use a lambda-expression:
In fact, in your first example, you omit
new Runnable()
.