The essential observation here is that your problem involves a non-isomorphic transformation: a single input element may map to zero, one, or two output elements. Whenever you notice this, you should immediately start looking for a solution which involves flatMap instead of map because that's the only way to achieve such a general transformation. In your particular case you can first apply filter for a one-to-zero element mapping, then flatMap for one-to-two mapping:

List<Integer> result =
    IntStream.rangeClosed(1, 10)
             .filter(i -> 10 % i == 0)
             .flatMap(i -> i == 5 ? IntStream.of(i) : IntStream.of(i, 10 / i))
             .boxed()
             .collect(toList());

(assuming import static java.util.stream.Collectors.toList)

Answer from Marko Topolnik on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › tutorial › java › javaOO › lambdaexpressions.html
Lambda Expressions (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
If the Person instance does satisfy the criteria specified by tester, the method printPerson is invoked on the Person instance. Instead of invoking the method printPerson, you can specify a different action to perform on those Person instances that satisfy the criteria specified by tester.
🌐
GeeksforGeeks
geeksforgeeks.org › java › lambda-expressions-java-8
Java Lambda Expressions - GeeksforGeeks
This is a zero-parameter lambda expression! ... It is not mandatory to use parentheses if the type of that variable can be inferred from the context. Parentheses are optional if the compiler can infer the parameter type from the functional interface. ... import java.util.ArrayList; public class GFG{ public static void main(String[] args){ ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); System.out.println("All elements:"); list.forEach(n -> System.out.println(n)); System.out.println("Even elements:"); list.forEach(n -> { if (n % 2 == 0) System.out.println(n); }); } }
Published   3 weeks ago
🌐
W3Schools
w3schools.com › java › java_lambda.asp
Java Lambda Expressions
Lambda Expressions were added in Java 8. A lambda expression is a short block of code that takes in parameters and returns a value. Lambdas look similar to methods, but they do not need a name, and they can be written right inside a method body. The simplest lambda expression contains a single parameter and an expression: ... Simple expressions must return a value immediately. They cannot contain multiple statements, such as loops or if conditions.
🌐
Blogger
javarevisited.blogspot.com › 2014 › 02 › 10-example-of-lambda-expressions-in-java8.html
10 Example of Lambda Expressions and Streams in Java 8
September 21, 2021 - This example brings us the syntax of lambda expression in Java 8. You can write following kind of code using lambdas : (params) -> expression (params) -> statement (params) -> { statements } for example, if your method doesn't change/write a ...
🌐
Oracle
oracle.com › java › technical details
Java 8: Lambdas, Part 1
Such is the case with the Comparator example in Listing 5. If the target type is a Comparator<String>, the objects passed in to the lambda must be strings (or some subtype); otherwise, the code wouldn’t compile in the first place. (This isn’t new, by the way—this is “Inheritance 101.”) In this case, then, the String declarations in front of the lhs and rhs parameters are entirely redundant and, thanks to Java 8...
🌐
Oracle
oracle.com › webfolder › technetwork › tutorials › obe › java › lambda-quickstart › index.html
Java SE 8: Lambda Quick Start
The OBE finishes up with a review of how the Java collection has been updated with lambda expressions. The source code for all examples is provided to you. The following is a list of hardware and software requirements: ... To run the examples, you must have an early access version of JDK 8 and a copy of NetBeans 7.4 or later.
🌐
Baeldung
baeldung.com › home › java › lambda expressions and functional interfaces: tips and best practices
Lambda Expressions and Functional Interfaces: Tips and Best Practices | Baeldung
December 16, 2023 - This code is legal, as total variable ... state after execution of the lambda? No! Keep this example as a reminder to avoid code that can cause unexpected mutations. In this article, we explored some of the best practices and pitfalls in Java 8’s lambda expressions and functional ...
Find elsewhere
Top answer
1 of 4
64

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 ->).

2 of 4
13

The syntax is

(parameter_list_here) -> { stuff_to_do; }

The curly braces can be omitted if it's a single expression. The regular parentheses around the parameter list can be omitted if it's a single parameter.

The syntax only works for all functional interfaces. The @FunctionalInterface annotation tells the compiler that you intend to write such an interface and gives a compile error if you do not meet the requirement(s) - for example it must only have 1 overrideable method.

@FunctionalInterface
interface TestInterface {
    void dostuff();
}

Runnable is also declared like that. Other interfaces are not, and they cannot be used with lambda functions.

Now that we've made a new functional interface with a method that takes no parameters, how about we test the question you had about "collision" in the signatures?

public class Main {
    private void test(Runnable r) {

    }
    private void test(TestInterface ti) {

    }
    public static void main(String[] args) { 
        test(() -> { System.out.println("test");})
    }

    @FunctionalInterface
    interface TestInterface {
        void dostuff();
    }
}

Result: compile error: ambigouous call to method test.

You see, the compiler/VM(if done runtime) finds the appropriate methods and their parameter list and sees if the parameter is a functional interface and if it is it creates an anonymous implementation of that interface. Technically (in byte code) it's different from an anonymous class, but otherwise identical (you won't see Main$1.class files).

Your example code (courtesy of Netbeans) can also be replaced with

SwingUtilities.invokeLater(MainAppJFrame::new);

Btw. :)

🌐
TheServerSide
theserverside.com › video › A-simple-Java-8-Predicate-lambda-interface-with-examples
Simple Java 8 Predicate example with lambda expressions and interfaces | TheServerSide
Compared with the traditional methods for interface creation, there's no debate that lambda expressions are much more concise. Here is the full Java Predicate example implemented with a lambda expression:
🌐
Programiz
programiz.com › java-programming › lambda-expression
Java Lambda Expressions (With Examples)
In this article, we will learn about Java lambda expression and the use of lambda expression with functional interfaces, generic functional interface, and stream API with the help of examples.
Top answer
1 of 16
337

Lambdas are purely a call-site construct: the recipient of the lambda does not need to know that a Lambda is involved, instead it accepts an Interface with the appropriate method.

In other words, you define or use a functional interface (i.e. an interface with a single method) that accepts and returns exactly what you want.

Since Java 8 there is a set of commonly-used interface types in java.util.function.

For this specific use case there's java.util.function.IntBinaryOperator with a single int applyAsInt(int left, int right) method, so you could write your method like this:

static int method(IntBinaryOperator op){
    return op.applyAsInt(5, 10);
}

But you can just as well define your own interface and use it like this:

public interface TwoArgIntOperator {
    public int op(int a, int b);
}

//elsewhere:
static int method(TwoArgIntOperator operator) {
    return operator.op(5, 10);
}

Then call the method with a lambda as parameter:

public static void main(String[] args) {
    TwoArgIntOperator addTwoInts = (a, b) -> a + b;
    int result = method(addTwoInts);
    System.out.println("Result: " + result);
}

Using your own interface has the advantage that you can have names that more clearly indicate the intent.

2 of 16
78

To use Lambda expression you need to either create your own functional interface or use Java functional interface for operation that require two integer and return as value. IntBinaryOperator

Using user defined functional interface

interface TwoArgInterface {

    public int operation(int a, int b);
}

public class MyClass {

    public static void main(String javalatte[]) {
        // this is lambda expression
        TwoArgInterface plusOperation = (a, b) -> a + b;
        System.out.println("Sum of 10,34 : " + plusOperation.operation(10, 34));

    }
}

Using Java functional interface

import java.util.function.IntBinaryOperator;

public class MyClass1 {

    static void main(String javalatte[]) {
        // this is lambda expression
        IntBinaryOperator plusOperation = (a, b) -> a + b;
        System.out.println("Sum of 10,34 : " + plusOperation.applyAsInt(10, 34));

    }
}
🌐
Readthedocs
java-8-tips.readthedocs.io › en › stable › lambdas.html
3. Lambdas — Java 8 tips 1.0 documentation
Java 8 has enhanced this type inferencing technique to deal with such wiered scenarios. Now let’s see how type inferencing works in lambda expressions. The type of lambda is deduced from the context where it is used. If we take our earlier example of Runnable and Callable, the signature of lambda expression matches with the singature of run() and call() methods.
🌐
DZone
dzone.com › coding › java › java 8: lambda functions—usage and examples
Java 8: Lambda Functions—Usage and Examples
May 4, 2016 - To support lambdas, Java has introduced a new operator “->”, also known as lambda operator or arrow operator. This arrow operator is required because we need to syntactically separate the parameter from the body. LambdaBody can be an expression or a block. The body could consist of single statement (in that case no explicit curly braces defining a block are required); such a lambda body is known as an "expression lambda." If ...
🌐
Medium
devcookies.medium.com › a-complete-guide-to-lambda-expressions-in-java-0aea2e1cea42
A Complete Guide to Lambda Expressions in Java
December 3, 2024 - Lambda expressions were introduced in Java 8 to enable functional programming and simplify the verbosity of anonymous classes. They allow you to write concise, functional-style code that is both readable and expressive. This guide will take you through the concepts, syntax, use cases, and practical examples of lambda expressions.
Top answer
1 of 5
39

As it almost but not really matches Optional, maybe you might reconsider the logic:

Java 8 has a limited expressiveness:

Optional<Elem> element = ...
element.ifPresent(el -> System.out.println("Present " + el);
System.out.println(element.orElse(DEFAULT_ELEM));

Here the map might restrict the view on the element:

element.map(el -> el.mySpecialView()).ifPresent(System.out::println);

Java 9:

element.ifPresentOrElse(el -> System.out.println("Present " + el,
                        () -> System.out.println("Not present"));

In general the two branches are asymmetric.

2 of 5
21

It's called a 'fluent interface'. Simply change the return type and return this; to allow you to chain the methods:

public MyClass ifExist(Consumer<Element> consumer) {
    if (exist()) {
        consumer.accept(this);
    }
    return this;
}

public MyClass ifNotExist(Consumer<Element> consumer) {
    if (!exist()) {
        consumer.accept(this);
    }
    return this;
}

You could get a bit fancier and return an intermediate type:

interface Else<T>
{
    public void otherwise(Consumer<T> consumer); // 'else' is a keyword
}

class DefaultElse<T> implements Else<T>
{
    private final T item;

    DefaultElse(final T item) { this.item = item; }

    public void otherwise(Consumer<T> consumer)
    {
        consumer.accept(item);
    }
}

class NoopElse<T> implements Else<T>
{
    public void otherwise(Consumer<T> consumer) { }
}

public Else<MyClass> ifExist(Consumer<Element> consumer) {
    if (exist()) {
        consumer.accept(this);
        return new NoopElse<>();
    }
    return new DefaultElse<>(this);
}

Sample usage:

element.ifExist(el -> {
    //do something
})
.otherwise(el -> {
    //do something else
});
🌐
Tutorialspoint
tutorialspoint.com › java › java-lambda-expressions.htm
Java - Lambda Expressions
Lambda expression throws a compilation error, if a variable is assigned a value the second time. In this example, we've one functional interface GreetingService with a method sayMessage, which we've used to print a message to the console.
🌐
Object Computing
objectcomputing.com › resources › publications › sett › february-2013-java-8-project-lambda
Java 8 Project Lambda | Object Computing, Inc.
Here a lambda expression is assigned to a Runnable and implements the Runnable.run() method. The compiler determines what type the lambda should be by the type of the target (Runnable in this case). This is a simple instance of target typing. Contrast this with how you would have to code the above example in Java 7 using an anonymous inner class.