Is there a default variable placeholder for lambdas in java8, like _
for scala?
Here is scala example:
case class Person(name:String, age:Int)
val people = List(Person("Jack", 35), Person("Arjun", 16), Person("Sasha", 13), Person("Sara", 8))
val teens = people.filter(_.age >= 13).filter(_.age <= 19)
Assuming there is a Person class defined, here is java example:
List<Person> people = Arrays.asList(new Person("Jack", 35), new Person("Arjun", 16), new Person("Sasha", 13), new Person("Sara", 8));
List<Person> teens = people.stream()
.filter(p -> (p.getAge() >= 13 && p.getAge() <= 19))
.collect(Collectors.toList());
Is there a way to write the filter in last line without defining variable p
. Obviously this is not a big issue, but just curious. I also understand that I could write a method in Person class like isTeenager
and pass that to lambda, but that's not the point either. Just want to know if there is a default variable placeholder for lambdas in java8.
A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.
Java lambdas can capture the following types of variables: Local variables. Instance variables. Static variables.
What is the return type of lambda expression? Explanation: Lambda expression enables us to pass functionality as an argument to another method, such as what action should be taken when someone clicks a button. 4.
Introduction. Lambda expressions are a new and important feature included in Java SE 8. They provide a clear and concise way to represent one method interface using an expression. Lambda expressions also improve the Collection libraries making it easier to iterate through, filter, and extract data from a Collection .
It's been proposed and rejected:
wunderbars were considered and (overwhelmingly) rejected by the EG.
There isn't, no. You could use a method reference to make it a bit closer; for that you would define a boolean method isATeen(Person p)
and then do something like this:
List<Person> teens = people.stream()
.filter(Person::isATeen)
.collect(Collectors.toList());
(Assuming that you defined the method is defined in Person. You could define it elsewhere.)
That way you don't have to explicitly create a name for the instance of Person
in the filter. You do of course do so in the method, so it's not much better.
UPDATE: With JEP 302, Phase 2 in JDK 9 the underscore has actually become an illegal name for a variable in any position. That way, future Java versions may use _
as a default placeholder for lambdas in a similar way to languages such as Scala. Or they may use it differently or not at all. We'll have to wait an see.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With