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.

Answer from Joachim Sauer on Stack Overflow
Top answer
1 of 16
338

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

    }
}
🌐
Oracle
docs.oracle.com › javase › tutorial › java › javaOO › lambdaexpressions.html
Lambda Expressions (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
In addition, aggregate operations typically accept lambda expressions as parameters, enabling you to customize how they behave. For a more thorough discussion of aggregate operations, see the Aggregate Operations lesson. To process events in a graphical user interface (GUI) application, such ...
Discussions

Can someone explain lambdas?
On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: Limiting your involvement with Reddit, or Temporarily refraining from using Reddit Cancelling your subscription of Reddit Premium as a way to voice your protest. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnprogramming
18
50
November 14, 2023
java - Pass function as parameter (Lambda) - Stack Overflow
I'm trying to understand Java 8's Lambda expressions. In the example, I want to parse a number of files. For each file, I need to create a new instance of the particular template (which is the same... More on stackoverflow.com
🌐 stackoverflow.com
April 26, 2017
Lambda Parameter in java - Stack Overflow
My quest is how can I have an lambda expression as a parameter in a function?? My intention is, when I execute the sum method the parameter in method accept is taken and used by the object continua... More on stackoverflow.com
🌐 stackoverflow.com
How to get Parameter Store values in Lambda code?

If you’re getting encrypted values, whatever IAM principal is making the call to parameter store also needs access to kms:Decrypt on the key used to encrypt the parameters you’re fetching.

More on reddit.com
🌐 r/aws
7
7
May 31, 2019
🌐
W3Schools
w3schools.com › java › java_lambda.asp
Java Lambda Expressions
import java.util.ArrayList; import ... } } ... You can also pass a lambda expression to a method. The method's parameter must be a functional interface....
🌐
Programiz
programiz.com › java-programming › examples › lambda-expression-as-method-parameter
Java Program to pass lambda expression as a method argument
import java.util.ArrayList; class Main { public static void main(String[] args) { // create an ArrayList ArrayList<String> languages = new ArrayList<>(); // add elements to the ArrayList languages.add("java"); languages.add("swift"); languages.add("python"); System.out.println("ArrayList: " + languages); // pass lambda expression as parameter to replaceAll() method languages.replaceAll(e -> e.toUpperCase()); System.out.println("Updated ArrayList: " + languages); } } Output ·
🌐
GeeksforGeeks
geeksforgeeks.org › java › lambda-expressions-java-8
Java - Lambda Expressions Parameters - GeeksforGeeks
When there is more than one statement, then these must be enclosed in curly brackets (a code block) and the return type of the anonymous function is the same as the type of the value returned within the code block, or void if nothing is returned. These are for single-line lambda expressions having void return type. Type 1: No Parameter.
Published: July 23, 2025
🌐
Jenkov
jenkov.com › tutorials › java › lambda-expressions.html
Java Lambda Expressions
From Java 11 var can also be used for lambda parameter types. Here is an example of using the Java var keyword as parameter types in a lambda expression: Function<String, String> toLowerCase = (var input) -> input.toLowerCase();
🌐
Techndeck
techndeck.com › java-pass-lambda-as-parameter-to-method-how-to-java8
Java 8 - How to Pass Lambda as a Parameter - Techndeck
April 18, 2022 - In order to pass Lambda expression as a Method Parameter, the type of method parameter that receives must be of type of the Functional Interface.
Find elsewhere
🌐
Baeldung
baeldung.com › home › java › core java › lambda expressions and functional interfaces: tips and best practices
Lambda Expressions and Functional Interfaces: Tips and Best Practices | Baeldung
December 16, 2023 - Functional interfaces, which are gathered in the java.util.function package, satisfy most developers’ needs in providing target types for lambda expressions and method references. Each of these interfaces is general and abstract, making them easy to adapt to almost any lambda expression. Developers should explore this package before creating new functional interfaces. ... In addition, we have a method add() in some class UseFoo, which takes this interface as a parameter...
🌐
BestProg
bestprog.net › home › java › theory › java. passing a lambda expression to a method as a parameter. examples
Java. Passing a lambda-expression to a method as a parameter. Examples | BestProg
December 19, 2020 - A lambda expression can be passed to a method as an argument. The declaration of such a method must contain a reference to the corresponding functional interface. This reference is obtained as a parameter of the method that processes the lambda expression.
🌐
TutorialsPoint
tutorialspoint.com › how-to-pass-a-lambda-expression-as-a-method-parameter-in-java
How can we pass lambda expression in a method in Java?
A lambda expression passed in a method that has an argument of type of functional interface. If we need to pass a lambda expression as an argument, the type of parameter receiving the lambda expression argument must be of a functional interface type.
🌐
Netjstech
netjstech.com › 2015 › 06 › lambda-expression-as-method-parameter-java-8.html
Java Lambda Expression as Method Parameter | Tech Tutorials
December 22, 2020 - functional interface, you can pass a lambda wherever such an interface is expected, including as a method argument. To pass a lambda expression as a method parameter in Java, the type of the method argument, which receives the lambda expression as a parameter, must be of functional interface type.
🌐
Baeldung
baeldung.com › home › java › core java › how to pass method as parameter in java
How to Pass Method as Parameter in Java | Baeldung
July 11, 2024 - In Java, we can pass a method as a parameter to another method using functional programming concepts, specifically using lambda expressions, method references, and functional interfaces.
🌐
Medium
gelopfalcon.medium.com › best-practices-when-you-use-lambda-expressions-in-java-f51e96d44b25
Best practices when you use Lambda expressions in Java | by Gerardo Lopez Falcón | Medium
June 25, 2018 - Foo foo = parameter -> { String result = "Something " + parameter;//many lines of codereturn result;}; However, please don’t use this “one-line lambda” rule as dogma. If you have two or three lines in lambda’s definition, it may not be valuable to extract that code into another method. In this post, we saw some best practices and pitfalls in Java 8’s lambda expressions and functional interfaces.
🌐
Rice
clear.rice.edu › comp310 › JavaResources › lambdas.html
Lambda Functions
This associated interface is related to the lambda function only in that it is the "target" type to which the lambda is being assigned, either by variable assignment or by passing the lambda as an input parameter or output parameter of a method which is typed to that interface.
🌐
Educative
educative.io › blog › java-lambda-expression-tutorial
Java lambda expression tutorial: Functional programming in Java
Today, we’ll help you get started ... anonymous function, meaning that they have no name or identifier. They can be passed as a parameter to another function....
🌐
Medium
medium.com › @kumar.atul.2122 › java-8-lambda-functional-interface-method-reference-stream-api-and-optional-class-f685143635fb
Java 8: lambda, functional interface, method reference, Stream API and Optional class | by Atul Kumar | Medium
February 19, 2023 - Lambda functions are used to enable functional programming in Java, which is a programming paradigm that emphasizes the use of functions and immutable data structures. ... The parameters are a comma-separated ...
🌐
Reddit
reddit.com › r/learnprogramming › can someone explain lambdas?
r/learnprogramming on Reddit: Can someone explain lambdas?
November 14, 2023 -

So I’m reading a book on Java, and it’s talking about lambdas. The syntax seems simple enough, but the author hasn’t described why you would use them over a regular function. They’re being used in the context of functions that don’t have bodies (abstracts, I think?), but I don’t understand why I would use those either.

Top answer
1 of 16
61
Lambdas are typically used when you're passing a callback function as a parameter to another object or method. Technically, functions in Java are not objects, so a "lambda function" actually gives you an object that implements an interface. There are other ways to do this, but lambdas are very concise and keep the code of the callback "inline" at the point where you're using it. Consider, for instance, the Swing JButton class. To make the button actually do something when clicked, you call addActionListener which expects as its parameter an implementation of the ActionListener interface. Say you want to print the string "Hello world!" when the button is clicked. You could write a whole separate HelloWorldActionListener class that implements ActionListener. Or you could write it as an inline anonymous class: button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Hello world!"); } }); A lambda function lets you do the same thing much more concisely: button.addActionListener(e -> System.out.println("Hello world!"));
2 of 16
18
Lambdas are basically anonymous, ad-hoc functions which are treated as first-class variables and can be passed around like any other object. They allow you to inject behavior as a dependency/parameter. They are very useful for cutting down on boilerplate. For example, let's say you have the following boilerplate in C#: StartTimer(); result = DoSomething(); StopTimer(); LogResultAndTime(result); StartTimer(); result = DoSomethingElse(); StopTimer(); LogResultAndTime(result); //ad nauseum Creating a regular method like so: void BoilerplateCode(int result) { StartTimer(); //What do you put here? StopTimer(); LogResultAndTime(result); //result was already calculated before it was passed in, so the result was not properly timed! } Will not work. However, if you use a lambda, you can make it work: void Boilerplate(Func lambda) { StartTimer(); var result = lambda(); //Invoke the lambda on behalf of the caller so that we can time the function that was passed in. StopTimer(); LogResultAndTime(result); } //Usage example: Boilerplate(() => DoSomething()/*This does not get executed until the lambda is invoked*/); Boilerplate(() => DoSomethingElse()); Boilerplate(() => DoSomethingOther()); // ad nauseum As you can see, using a lambda allows me to only define my boilerplate code once, instead of needing to repeat it each time I want to use it. This allows me to easily make an enhancement, such as adding exception handling: void Boilerplate(Func lambda) { try { StartTimer(); var result = lambda(); //Invoke the lambda on behalf of the caller so that we can time the function that was passed in. StopTimer(); LogResultAndTime(result); } catch (Exception ex) { LogExceptionAndTime(ex); } } And all usages of the boilerplate get the updated/enhanced behavior immediately without the need for me to hunt down every instance of the boilerplate and update them by hand. Lambdas can also capture contextual data from the local scope, which allows your boilerplate to ignore implementation details about your lambda, like parameters and dependencies. var myParam = CalculateExpensiveDependency(); Boilerplate(() => DoSomething(myParam)); Boilerplate(() => DoSomethingElse(myParam)); Because we are using lambdas, Boilerplate() doesn't need to know anything about the parameters which DoSomething() or DoSomethingElse() requires. This reduces coupling, and makes your code more resusable, more resilient and more maintainable
🌐
Java Guides
javaguides.net › 2024 › 09 › how-to-pass-lambda-expression-as-parameters-in-java.html
How to Pass Lambda Expression as a Parameter in Java 8
September 9, 2024 - Lambda expressions in Java 8 can be passed as parameters to methods, providing a clean and efficient way to pass behavior (functions) as arguments.
Top answer
1 of 2
3

Interestingly enough, your current lambda expression will work for this (barring the fix to the typo of system.out.println). The below is merely a more concise way to express it.

Effectively, you're writing out a method that takes in two values, produces one, and places it in some sort of consumer. That consumer could be a collection, some function that can handle the result, or another object.

Let's take lambdas out of the equation for a moment and write this out with an anonymous class.

x.sum(1, 2, new Consumer<Integer>() {
    @Override
    public void accept(final Integer value) {
        // what should go here?
    }
});

We need to tell this result where to go. We've got a few options:

  • A Collection (List, Set, etc)
  • A new reference object
  • A method reference that accepts the parameter

Let's take the simplest approach and simply print it out.

x.sum(1, 2, new Consumer<Integer>() {
    @Override
    public void accept(final Integer value) {
        System.out.println(value);
    }
});

Now, this makes some sense - we're taking the result of two numbers, adding them together, and then printing the result to the screen.

Let's put lambdas back into the mix. This can be expressed in terms of a lambda in this manner:

x.sum(1, 2, System.out::println);

Effectively, whatever resultant value we get back, we wish to then allow the println method to consume it.

2 of 2
0

I think I understand what you are trying to do. What is important to understand in your problem is - "what is the behavior we want to pass as Lambda?". In your case the answer to this question is "print the value of the summation passed to the Lambda/Consumer instance".

To achieve that we need to create a Lambda instance which does the printing and then pass it to the X.sum method. Written below is the code which achieves the same

//ExampleClass.java
import java.util.function.Consumer;
public class ExampleClass {
  public static void main(String[] args) {
    X x = new X();
    Consumer<Integer> consumerInstance=(value) -> System.out.println("Summation Result is ->value");
    x.sum(1, 2, consumerInstance);
  }
 }

//X.java
import java.util.function.Consumer;
public class X{
  public void sum(int value1,int value2,Consumer<Integer> continuation){
    continuation.accept(value1+value2);
  }
}

For basic understanding of Lambda Expressions you can refer this link - http://www.javabrahman.com/java-8/lambda-expressions-java-8-explained-examples/ .

(Note - www.javabrahman.com is a tech blog owned by me.)