Lambdas are just a way to create a type for a function. Keep in mind that a function has no "values" and hasn't been executed yet.

You can apply any Lambda to a set of values by calling it's apply method. It will then take the inputs (parameters to apply) and return the value as the result. A Lambda for a function that looks like this

(Coordinate x) -> { return new Distance(Math.sqrt(x.x * x.x + x.y * x.y)) }

would return the distance to the origin for a Coordinate assuming a Coordinate looked a little like

public class Coordinate {
   public double x;
   public double y;
}

and Distance looked a bit like like

public class Distance {

   public Distance(double value) {
      ... whatever the implementation is ...
   }

}

This function has a type conversion in it, it takes a Coordinate and returns a Distance. This means it fits the java "interface" of

Function<Coordinate, Distance>

and just by writing this Lambda

(Coordinate x) -> { return new Distance(Math.sqrt(x.x * x.x + x.y * x.y)) }

The Java compiler will generate some unnamed class of type Function<Coordinate, Distance> and instantiate an instance (create an object the class) to use in the context of the location of the Lambda.

Now if that lambda is within a method of a stream, such that the stream's parameter types are compatible, the stream will (in some manner) call apply on each value the stream is handling. Those values come from a Supplier which is basically an object that has a T get() method.

  1. Stream calls the Supplier's get() method.
  2. Stream has a method .forEach( ... ) containing a lambda that consumes the get() type.
  3. Stream applies the value of get() to the lambda in forEach() by passing it into apply(value).
  4. Stream collects the result of apply(value)
  5. Stream returns from the .forEach(...) method a new stream with values typed to match the return value of the lambda in the forEach() method.
  6. Eventually, these values are passed into a Collector method which combines values into some sort of buffer. Sometimes a List, sometimes a single value.

Conveniences exist for various ways of simplifying the collectors. Conveniences exist for generating values without coding suppliers.
The lambda syntax itself is a convenience for not having to write an implementation of one of the "xxxFunction" interfaces, create an object of it, and pass it into the stream. Predicates are what they call Functions that return boolean values. There are even more convenience functions that work with predicates.

So, if you don't have a collection of data points to process, you probably shouldn't be using lambdas. If you do have a collection of data points to process, then keep in mind that streams and lambdas provide a new not-quite-like-a-loop way of processing them. They are guaranteed to be applied to all values, but the order of their application is not necessarily in the strong ordering that a traditional loop would apply. With the right options, you can effectively split the input into multiple chunks (spliterator vs iterator) and process the data in parallel.

Now that you have a quick overview of Lambdas, Streams, and the Functional interfaces, you can see that

(loc, newloc) -> Math.pow((loc.getX()-newloc.getX()), 2) + 
 Math.pow(loc.getY()-newloc.getY(), 2)+Math.pow(loc.getZ()-newloc.getZ(), 
 2));

wouldn't "do" anything, because at best it describes this

public class MyFunction implements Function<Location, Location, Double> {
    Double apply(Location first, Location second) {
       return Math.pow((first.getX()-second.getX()), 2)
              + Math.pow(first.getY()-second.getY(), 2)
              + Math.pow(first.getZ()-second.getZ(), 2)
    }
}

MyFunction myFunc = new MyFunction();

Which has the following problem"

  • It's a coding error as it's only creating the facility to transform locations, and never using it.

Using the facility would look like

double result = myFunc.apply(loc, newloc);

Now, the very astute readers will mention auto-boxing, but in reality the compiler would choose the ToDoubleBiFunction type, probably side-stepping some of the possible auto-boxing issues. I just didn't want to write the example up in the non-generic manner, as again, the primitive functional types are a convenience (and optimization) of the general "all object" description above.

Answer from Edwin Buck on Stack Overflow
🌐
W3Schools
w3schools.com › java › java_lambda.asp
Java Lambda Expressions
Calling the interface's method will then run the lambda expression: interface StringFunction { String run(String str); } public class Main { public static void main(String[] args) { StringFunction exclaim = (s) -> s + "!"; StringFunction ask = (s) -> s + "?"; printFormatted("Hello", exclaim); printFormatted("Hello", ask); } public static void printFormatted(String str, StringFunction format) { String result = format.run(str); System.out.println(result); } } ... In Java 8+, you can often replace an anonymous class with a lambda expression - but only if the interface is a functional interface (one abstract method).
Top answer
1 of 3
2

Lambdas are just a way to create a type for a function. Keep in mind that a function has no "values" and hasn't been executed yet.

You can apply any Lambda to a set of values by calling it's apply method. It will then take the inputs (parameters to apply) and return the value as the result. A Lambda for a function that looks like this

(Coordinate x) -> { return new Distance(Math.sqrt(x.x * x.x + x.y * x.y)) }

would return the distance to the origin for a Coordinate assuming a Coordinate looked a little like

public class Coordinate {
   public double x;
   public double y;
}

and Distance looked a bit like like

public class Distance {

   public Distance(double value) {
      ... whatever the implementation is ...
   }

}

This function has a type conversion in it, it takes a Coordinate and returns a Distance. This means it fits the java "interface" of

Function<Coordinate, Distance>

and just by writing this Lambda

(Coordinate x) -> { return new Distance(Math.sqrt(x.x * x.x + x.y * x.y)) }

The Java compiler will generate some unnamed class of type Function<Coordinate, Distance> and instantiate an instance (create an object the class) to use in the context of the location of the Lambda.

Now if that lambda is within a method of a stream, such that the stream's parameter types are compatible, the stream will (in some manner) call apply on each value the stream is handling. Those values come from a Supplier which is basically an object that has a T get() method.

  1. Stream calls the Supplier's get() method.
  2. Stream has a method .forEach( ... ) containing a lambda that consumes the get() type.
  3. Stream applies the value of get() to the lambda in forEach() by passing it into apply(value).
  4. Stream collects the result of apply(value)
  5. Stream returns from the .forEach(...) method a new stream with values typed to match the return value of the lambda in the forEach() method.
  6. Eventually, these values are passed into a Collector method which combines values into some sort of buffer. Sometimes a List, sometimes a single value.

Conveniences exist for various ways of simplifying the collectors. Conveniences exist for generating values without coding suppliers.
The lambda syntax itself is a convenience for not having to write an implementation of one of the "xxxFunction" interfaces, create an object of it, and pass it into the stream. Predicates are what they call Functions that return boolean values. There are even more convenience functions that work with predicates.

So, if you don't have a collection of data points to process, you probably shouldn't be using lambdas. If you do have a collection of data points to process, then keep in mind that streams and lambdas provide a new not-quite-like-a-loop way of processing them. They are guaranteed to be applied to all values, but the order of their application is not necessarily in the strong ordering that a traditional loop would apply. With the right options, you can effectively split the input into multiple chunks (spliterator vs iterator) and process the data in parallel.

Now that you have a quick overview of Lambdas, Streams, and the Functional interfaces, you can see that

(loc, newloc) -> Math.pow((loc.getX()-newloc.getX()), 2) + 
 Math.pow(loc.getY()-newloc.getY(), 2)+Math.pow(loc.getZ()-newloc.getZ(), 
 2));

wouldn't "do" anything, because at best it describes this

public class MyFunction implements Function<Location, Location, Double> {
    Double apply(Location first, Location second) {
       return Math.pow((first.getX()-second.getX()), 2)
              + Math.pow(first.getY()-second.getY(), 2)
              + Math.pow(first.getZ()-second.getZ(), 2)
    }
}

MyFunction myFunc = new MyFunction();

Which has the following problem"

  • It's a coding error as it's only creating the facility to transform locations, and never using it.

Using the facility would look like

double result = myFunc.apply(loc, newloc);

Now, the very astute readers will mention auto-boxing, but in reality the compiler would choose the ToDoubleBiFunction type, probably side-stepping some of the possible auto-boxing issues. I just didn't want to write the example up in the non-generic manner, as again, the primitive functional types are a convenience (and optimization) of the general "all object" description above.

2 of 3
1

Lambda expressions are used to generate anonymous functions. They can be used where a @FunctionalInterface is expected.

Read more about them here: https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

If you'd like your code to work you can assign your lambda to a BiFunction variable and then execute it passing in the loc and newloc.

public class mathprob {
    public static void main(String[] args) {
        Location _loc = player.getlocation();
        Location _newloc = player.getlocation();

        BiFunction<Location, Location, Double> lambdaExpression = (loc, newloc) ->  {
           return Math.pow((loc.getX()-newloc.getX()), 2) +
              Math.pow(loc.getY()-newloc.getY(), 2)+Math.pow(loc.getZ()-newloc.getZ(),
              2);
        };

        double result = lambdaExpression.apply(_loc, _newloc);
    }
}

Here is an example of how the equivalent method declaration would look like instead of using a lambda:

public class mathprob {
    public static void main(String[] args) {
        Location loc = player.getlocation();
        Location newloc = player.getlocation();
        double result = calculate(loc, newloc);
    }
    

    public static double calculate(Location loc, Location newloc) {     
        return
            Math.pow((loc.getX() - newloc.getX()), 2) + 
            Math.pow(loc.getY() - newloc.getY(), 2) + 
            Math.pow(loc.getZ() - newloc.getZ(), 2);
    }

}
Discussions

[Java] ELI5 Lambda expressions
Lambda expressions are, for the most part, a more concise way of writing something that previously would have required a class instance (usually an anonymous class) to implement. So if you understand how and why anonymous classes are used, you can figure out lambda expressions. If you don't, then your first step should be to understand those. Java does not have function pointers. Function pointers are used in C and C++ extensively. They are a way of passing functions to other functions. In Lisp you can do that directly, because functions are so-called "first class objects", but in C you have to pass a pointer to some function X and then the function you are calling can call X via the pointer. But, Java doesn't have these. What you do for Java is pass in an object with an implemented method and whatever you are calling will call the method in that class. This is done something like: someObject.foo(new Bonk() { void bonk(String who) { System.out.println("I'm bonking you, " + who); }); This looks a little confusing, but what we are doing is defining a new class (and not giving it a name) and creating an instance of that class at the same time, and then passing that instance to foo. You could do this as something like: class MyBonk implements Bonk { void bonk(String who) { System.out.println("I'm bonking you, " + who); } } MyBonk bonker = new MyBonk(); someObject.foo(bonker); But the first way is much, much terser, right? I love anonymous classes, but I'm a closet LISP programmer, so that would figure. Anyway, lambda functions are a mostly syntactic shortcut for anonymous classes (although there are JVM changes as well, for reasons that I have not investigated). If you have an anonymous class with just one method then it's pretty obvious that the purpose of that class is to call that method. Anonymous functions remove even more of the cruft and you say: someObject.foo(who -> System.out.println("I'm bonking you, " + who); And every LISP programmer in the world says "Wow, we figured this out over half a century ago". More on reddit.com
🌐 r/learnprogramming
12
37
July 14, 2016
Introduction to Lambda Expressions in Java
Resources for learning Java · My attempt to explain the need for Lambda Expressions in Java and how they work under the hood - More on reddit.com
🌐 r/learnjava
1
13
August 27, 2017
An in-depth look at Lambda expressions in Java

An actual in-depth look at Lambdas and Streams, Get a Taste of Lambdas and Get Addicted to Streams by Venkat Subramaniam

More on reddit.com
🌐 r/java
15
85
May 19, 2018
Java 8 idioms: Why the perfect lambda expression is just one line
It's funny how much "best practice" material for good FP or OOP programming boils down to the lessons taught first by structured programming. When a clickbaity article like this comes along on a "hot new idea" like Java 8 lambdas, and it boils down to "refactor your code into functions", well... it suddenly makes me feel like we haven't come very far after all. More on reddit.com
🌐 r/java
47
117
August 3, 2017
🌐
Oracle
docs.oracle.com › javase › tutorial › java › javaOO › lambdaexpressions.html
Lambda Expressions (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
However, when the Java runtime invokes the method printPersonsWithPredicate, it's expecting a data type of Predicate<Person>, so the lambda expression is of this type. The data type that these methods expect is called the target type. To determine the type of a lambda expression, the Java compiler uses the target type of the context or situation in which the lambda expression was found.
🌐
TutorialsPoint
tutorialspoint.com › article › how-can-we-write-a-multiline-lambda-expression-in-java
How can we write a multiline lambda expression in Java?
If the lambda expression returns a result then the return keyword is also required. ([comma seperated argument-list]) -> { multiline statements } interface Employee { String displayName(String s); } public class MultilineLambdaTest { public static void main(String[] s) { Employee emp = <strong>(x) -> {</strong> // Lambda Expression with multiple lines x = "Jai " + x; System.out.println(x); return x; }; emp.displayName("Adithya"); } }
🌐
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 can only be used with functional interfaces. Java 8 introduced several functional interfaces in the java.util.function package.
🌐
Programiz
programiz.com › java-programming › lambda-expression
Java Lambda Expressions (With Examples)
Here, the method does not have any parameters. Hence, the left side of the operator includes an empty parameter. The right side is the lambda body that specifies the action of the lambda expression. In this case, it returns the value 3.1415. In Java, the lambda body is of two types.
🌐
Educative
educative.io › blog › java-lambda-expression-tutorial
Java lambda expression tutorial: Functional programming in Java
Function Composition: Multiple simple functions can be strung together in different orders to create complex functions. Simple functions complete a single step that may be shared across multiple tasks, while complex functions complete an entire task. Lambda expressions help us achieve pure functions, immutability, and first-class functions principles in Java.
Find elsewhere
🌐
Jenkov
jenkov.com › tutorials › java › lambda-expressions.html
Java Lambda Expressions
If the lambda expression matches the parameter type (in this case the StateChangeListener interface) , then the lambda expression is turned into a function that implements the same interface as that parameter. Java lambda expressions can only be used where the type they are matched against is a single method interface...
🌐
CodeGym
codegym.cc › java blog › java expressions › an explanation of lambda expressions in java. with exampl...
An explanation of lambda expressions in Java. With examples and tasks. Part 1
January 13, 2022 - There are interfaces that don't have a single method (so-called marker interfaces such as Serializable). Interfaces that have only one method are also called functional interfaces. In Java 8, they are even marked with a special annotation: @FunctionalInterface. It is these single-method interfaces that are suitable as target types for lambda expressions.
🌐
GeeksforGeeks
geeksforgeeks.org › java › lambda-expressions-java-8
Java Lambda Expressions - GeeksforGeeks
It is mainly used with lambda expressions and method references to enable functional programming in Java.
Published: August 29, 2026
🌐
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.
🌐
Medium
medium.com › @bubu.tripathy › effective-lambda-expressions-in-java-2d4061dde77a
Effective Lambda Expressions in Java | by Bubu Tripathy | Medium
March 11, 2023 - They are a concise way to express functions that can be used as data and provide a more functional approach to programming. Lambda expressions can be used in a variety of ways, from simple expressions to complex functions.
🌐
DZone
dzone.com › coding › java › lambda expression in java 8
Lambda Expression in Java 8
September 3, 2020 - These are very useful and java developers use these in frequent manner to build their java application. ... How lambda function can be passed as function parameter. Please find the below code example. In the below code the first argument of the function “getEmployeeName” is a argument of type functional interface and to pass the parameter value we have used lambda expression while invoking the function.
🌐
Brilworks
brilworks.com › blog › lambda-expression-java
Lambda Expressions in Java: Syntax & Examples (2026 Guide)
June 9, 2026 - A lambda expression in Java is a short, anonymous block of code that implements a single-method (functional) interface. It lets you pass behaviour as an argument: instead of writing a verbose anonymous inner class, you write (params) -> body.
Price: $$
Address: 503, Fortune Business Hub, Science City Road, Sola, 380060, Ahmedabad
🌐
Stackabyte
stackabyte.com › tutorials › Java › java-lambda-expressions-tutorial
Java Lambda Expressions: Complete Guide with Examples | Stack a Byte
June 21, 2025 - Lambda expressions enable functional programming patterns in Java, making code more declarative and often more readable. Lambda expressions are particularly powerful when used with the Streams API for processing collections.
🌐
Medium
medium.com › @AlexanderObregon › lambda-expressions-and-functional-programming-in-java-ce81613380a5
Lambda Expressions and Functional Programming in Java
December 5, 2023 - If the context allows, Java can ... that performs a simple task, or they can be more complex, accepting multiple parameters and executing a block of code....
🌐
Java2Blog
java2blog.com › home › core java › java 8 › lambda expressions in java 8
Lambda Expressions in Java 8 - Java2Blog
February 16, 2024 - Let’s say we need to sort list ... Movie.java · Code to sort list of movies by name using comparator · The problem with Anonymous Comparator lies in its syntax. Each time we want to sort a list using a comparator, remembering the bulky syntax becomes necessary. Generally, the main issue with Anonymous classes is their syntax; even for very simple operations, complex code is required. To address this, JDK introduced a new feature called Lambda Expressions...
🌐
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 - Prior to Java 8, if you want to ... expression replaces anonymous classes and removes all boilerplate, enabling you to write code in a functional style, which is sometimes more readable and expression....
🌐
E Innovations
eginnovations.com › blog › demystifying-java-lambda-expressions
Demystifying Java Lambda Expressions | eG Innovations
February 29, 2024 - In normal class loading, the bytecode is loaded via the “transform” method. However, for Java lambda expressions, the Java bytecode is loaded via the “bootstrap” method. This adds complexity to the instrumentation process.
🌐
Intellipaat
intellipaat.com › home › blog › java lambda expressions
Java Lambda Expressions - Explained with Examples
3 weeks ago - Exception in thread "main" ...ch(Arrays.java:1510) lambda$main$0 is an anonymous lambda method inside the main method. Solution: Add descriptive logs to track execution in lambdas. ... Code Copied! ... Visibility during debugging is enhanced through logging in lambdas. Rather than inlining complex logic in lambdas, use method references: ... Code Copied! ... Named methods enhance stack traces. Recursion is calling a function that calls itself. Lambda expressions cannot recurse ...