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
The simplest lambda expression ... statements, such as loops or if conditions. To do more complex work, use a code block with curly braces....
🌐
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.
Discussions

How do you use a lambda expresion with complex math in java - Stack Overflow
hello i a trying to compare to values after i apply a lambda experrsion to them im trying to compare a location of a player and another to see the distance between them and im having trouble with l... More on stackoverflow.com
🌐 stackoverflow.com
[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
High level overview of Lambda Expressions in Java 8

Personally, I find it easier to think of lambdas as just syntactic sugar for interfaces with a single abstract method. It's not clear from the post when they can be used (e.g. not for abstract classes). Also, converting a for-loop to use forEach doesn't require a lambda. It's much cleaner with lambdas, but I could see someone getting confused as to when lambdas can/should be used.

More on reddit.com
🌐 r/programming
42
149
December 25, 2016
🌐
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
🌐
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.
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);
    }

}
🌐
Medium
devcookies.medium.com › a-complete-guide-to-lambda-expressions-in-java-0aea2e1cea42
A Complete Guide to Lambda Expressions in Java
December 3, 2024 - A Complete Guide to Lambda Expressions in Java Lambda expressions were introduced in Java 8 to enable functional programming and simplify the verbosity of anonymous classes. They allow you to write …
🌐
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 - But in the case of mutable object variables, a state could be changed inside lambda expressions. ... This code is legal, as total variable remains “effectively final,” but will the object it references have the same 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 interfaces.
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › article › how-can-we-write-a-multiline-lambda-expression-in-java
How can we write a multiline lambda expression in Java?
interface Employee { String displayName(String s); } public class MultilineLambdaTest { public static void main(String[] s) { Employee emp = (x) -> { // Lambda Expression with multiple lines x = "Jai " + x; System.out.println(x); return x; }; emp.displayName("Adithya"); } }
🌐
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...
🌐
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....
🌐
Educative
educative.io › blog › java-lambda-expression-tutorial
Java lambda expression tutorial: Functional programming in Java
March 10, 2025 - 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.
🌐
Brilworks
brilworks.com › blog › lambda-expression-java
Java Lambda Expression: What is it? With an example
You can have zero or more parameters, and the body can be a single expression or a block of statements enclosed in curly braces. Lambdas can only access final or effectively final local variables from the surrounding scope.
🌐
Dev.java
dev.java › learn › lambdas
Lambda Expressions - Dev.java
Creating and Combining Comparators Using Lambda Expressions.
🌐
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 ... in Java, making code more declarative and often more readable. Lambda expressions are particularly powerful when used with the Streams API for processing collections. Common use cases include event handling, collection processing, asynchronous programming, and implementing design patterns. Best practices include keeping lambdas short and focused, using descriptive parameter names, and extracting complex logic to named ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-use-lambdas-in-java
How to Use Lambdas in Java | DigitalOcean
February 28, 2024 - Method references are a shorthand notation for a lambda expression to call a method. They are considered more readable and recommended by the clean code best practices. ... However, not all lambdas are so simple and can be fitted on one line. You will likely have to use lambdas with more parameters and the execution block will be on more than just one line. That’s when the syntax becomes more complex...
🌐
Oracle
oracle.com › java › technical details
Java 8: Lambdas, Part 1
Syntax. A lambda in Java essentially consists of three parts: a parenthesized set of parameters, an arrow, and then a body, which can either be a single expression or a block of Java code. In the case of the example shown in Listing 2, run takes no parameters and returns void, so there are ...
🌐
Medium
medium.com › @bubu.tripathy › effective-lambda-expressions-in-java-2d4061dde77a
Effective Lambda Expressions in Java | by Bubu Tripathy | Medium
March 11, 2023 - ... Functional programming is a ... problems. In Java, Lambda expressions can be used to implement functional programming by creating and using functions as first-class objects....
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › lambda expressions in java
Java 8 Lambda Expression (with Examples)
October 1, 2022 - In general programming language, ... of parameters and the body. In Java, a lambda expression is an expression that represents an instance of a functional interface....
🌐
Scaler
scaler.com › home › topics › java › lambda expression in java
Lambda Expression in Java | Scaler Topics
May 4, 2023 - Lambda expression in java is an anonymous (no name) function that does not need to define the data type of input parameters and does not need to have a return type. Lambda expression in java implements the functional interface and it can be ...
🌐
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....