What Is the Breakdown for Java's Lambda Syntax

What is the breakdown for Java's lambda syntax?

Syntax is:

arguments -> body

where arguments can be either

  • ()

  • a single variable if the type of that variable can be inferred from the context

  • a sequence of variables, with or without types (or since Java 11, with var), in parentheses.

    Examples: (x), (x, y), (int x, int y), (var x, var y) (Java 11+).

    The following are invalid: (int x, y), (x, var y), (var x, int y)

and body can be either an expression or a {...} block with statements. The expression (other than a method or constructor call) is simply returned, i.e. () -> 2 is equivalent to () -> {return 2;}


In case of lambda expressions like () -> f() (the body is a method or constructor call expression):

  • if f() returns void, they are equivalent to () -> { f(); }

  • otherwise, they are equivalent to either () -> { f(); } or () -> { return f(); }). The compiler infers it from the calling context, but usually it will prefer the latter.

Therefore, if you have two methods: void handle(Supplier<T>) and void handle(Runnable), then:

  • handle(() -> { return f(); }) and handle(() -> x) will call the first one,

  • handle(() -> { f(); } will call the second one, and

  • handle(() -> f()):

    • if f() returns void or a type that is not convertible to T, then it will call the second one

    • if f() returns a type that is convertible to T, then it will call the first one


The compiler tries to match the type of the lambda to the context. I don't know the exact rules, but the answer to:

What would happen if there were two SwingUtilities.invokeLater methods which differ only in parameter list?

is: it depends on what would be those parameter lists. If the other invokeLater had also exactly one parameter and that parameter would be of type that is also an interface with one method of type void*(), well, then it would complain that it cannot figure out which method you mean.

Why are they written as they are? Well, I think it's because syntax in C# and Scala is almost the same (they use => rather than ->).

what does the - means in java

What you see there is a Lambda expression, a new feature that was added in Java 8.

There is too much to say about lambdas to put it all here, but in short it's a very concise way to add an anonymous class containing only a single method.

The method you mention there is functionally equivalent to:

static <T> UnaryOperator<T> identity() {
return new UnaryOperator<T>{
public T apply(T parameter){
return parameter;
}
}
}

The full tutorial is here: https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

How Runnable is created from Java8 lambda

A Lambda can be used in any place where a functional interface is required.
A functional interface is any interface with a single abstract method.

The lambda syntax used in this case is (arguments) -> {blockOfCodeOrExpression}. The parenthesis can be omitted in the case of a single argument, and the braces can be omitted in the case of a single command or expression.

In other words, () -> System.out.println("hello world"); is equivalent* here where a Runnable is expected to

 new Runnable(){      
@Override
public void run(){
System.out.println("Hello world one!");
}
};

*(I'm pretty sure that it is not bytecode-equivalent, but is equivalent in terms of functionality)

Which would be better in terms of performance Lambda or simple loop?

My advice would be:

  1. Use the style that you and your coworkers agree is most maintainable.

  2. If you and your colleagues are not yet comfortable with lambdas, keep learning.

  3. Don't obsess over performance. It is often not the most important thing.

Generally speaking, lambdas and streams provide a more concise and (once everyone is up to speed) more readable way of expressing this kind of algorithm. Performance is not the primary goal.

If performance does become an issue, then the standard advice is to code, test, benchmark, profile and optimize. And do it in that order! You can easily waste a lot time by optimizing at the coding stage, or by optimizing code that has minimal impact on overall application performance.

  • Let the application benchmarks tell you if you need to optimize at all.
  • Let the profiler point out the parts of your code that are worthy of the effort of optimization.

In this specific example, the performance difference is going to be too small to measure. And if you scaled up to a list of millions of elements, the performance will be dominated by the time taken to build the list and write the numbers. The different ways of iteration will only contribute a small part to the overall performance.


And for folks, who (despite all of the above) still want to know whether it is faster to use a lambda or a conventional loop, the best general answer is:

"It depends on all sorts of factors that 1) are not well understood, and 2) liable to change as Java compiler technology evolves.

We could give you an answer for a specific example with a specific Java major/minor/patch release, but it would be unwise to generalize.

What is the purpose of trailing lambda syntax (Kotlin)?

This syntax gives Kotlin great DSL capabilities, it makes functions look like language constructions. For example:

with(car) {
startUp()
goToDestination()
}

Here with looks like it is language construction, whereas it is a simple function, receiving lambda as the last parameter.

And this leads to such elegant things like Kotlin HTML DSL

what is the meaning of = () - in java?

() -> { is the opening of a no argument lambda expression and the }; is the end of the expression.



Related Topics



Leave a reply



Submit