Java Lambdas and Functional Interfaces
A six-line anonymous Discount becomes total -> total * 0.85. Lambdas with no, one and two parameters show which brackets and braces can go, a Runnable job runs between START and DONE, and two Comparator lambdas sort students by marks, then by name.
What you will learn
- Turn a one-method anonymous class into a lambda
- Write lambdas with no, one and two parameters, and know when brackets and braces are required
- Pass a lambda to a method as a Runnable and explain effectively final
- Sort a list with Comparator lambdas and thenComparing
Before you start
- Java interfaces
- Java nested, inner and anonymous classes
Think of a lambda as a sticky note of instructions you hand to a method. It cuts a lot of code, though it can look confusing at first. The trick is to see what Java can already work out for you.
Six lines fall away
package org.studyeasy.s05l06;
public class Ex01_AnonToLambda {
@FunctionalInterface
interface Discount { // ONE abstract method
double apply(double total);
}
public static void main(String[] args) {
// Before: an anonymous class, six lines for one rule
Discount festive = new Discount() {
@Override
public double apply(double total) {
return total * 0.90;
}
};
// After: a lambda, just the parameter and the body
Discount student = total -> total * 0.85;
System.out.println("Festive: " + festive.apply(2000.0));
System.out.println("Student: " + student.apply(2000.0));
}
}
Festive: 1800.0
Student: 1700.0
The left side already says Discount, and Discount has exactly one abstract method. So new Discount() and the override can go, since only one method can be meant. Java reads the types from Discount, and a single expression is the result, so double and return go too. What's left is the parameter, an arrow and the work. An interface with one abstract method is a functional interface; the @FunctionalInterface annotation is optional, but with it, Java checks that rule.
No parameters, one, or two
interface Greeting { void say(); } // nothing in, nothing out
interface Motto { String text(); } // nothing in, a String out
Greeting morning = () -> System.out.println("Good morning!");
Motto motto = () -> "Small step every day";
Empty brackets mean nothing goes in. Each call to morning.say() runs the body, so calling it twice prints "Good morning!" twice, and motto.text() hands back the String. Greeting bad = () -> "Hi"; fails: say returns void, so the body can't be a value.
interface Greeter { String greet(String name); }
Greeter g1 = (String name) -> { return "Hello, " + name; }; // full form
Greeter g2 = (name) -> "Hello, " + name; // no type, braces, return
Greeter g3 = name -> "Hello, " + name; // no brackets
interface Checker { boolean test(int number); }
Checker isEven = n -> n % 2 == 0; // any name works
All three Greeters print Hello, Maya, and isEven.test(8) is true. The name n is just a name.
interface Calculator { int apply(int a, int b); }
Calculator add = (a, b) -> a + b; // brackets required
Calculator minus = (int a, int b) -> a - b; // types for all, or none
Calculator withTax = (qty, price) -> { // several statements
int net = qty * price;
return net + net * 18 / 100; // add 18% tax
};
3 + 4 = 7
9 - 4 = 5
With tax: 885
Three items at 250 is 750, plus 135 tax, gives 885. More than one statement needs curly braces and return.
| Parameters | Brackets | Example |
|---|---|---|
| none | required: () | () -> "Small step every day" |
| one | optional | name -> "Hello, " + name |
| two or more | required | (a, b) -> a + b; a, b -> ... won't compile |
Hand the code to a method
package org.studyeasy.s05l06;
import java.util.List;
public class Ex05_RunnableTasks {
// Same START and DONE for every job: the job comes in as a Runnable
static void runJob(String name, Runnable job) {
System.out.println("START " + name);
job.run(); // the passed-in code runs here
System.out.println("DONE " + name);
}
public static void main(String[] args) {
String course = "Java Foundation"; // set once: effectively final
List<String> students = List.of("Aisha", "Tom", "Wei");
runJob("welcome emails", () -> {
for (String student : students) {
System.out.println(" Email: welcome, " + student);
}
});
runJob("class report", () -> System.out.println(
" " + course + ": " + students.size() + " students"));
}
}
START welcome emails
Email: welcome, Aisha
Email: welcome, Tom
Email: welcome, Wei
DONE welcome emails
START class report
Java Foundation: 3 students
DONE class report
Runnable is a built-in functional interface whose one method, run, takes nothing and returns nothing: code to run. runJob prints START and DONE around whatever job it receives. The lambdas use course and students from outside. Those are set once and never change, which Java calls effectively final. Change course afterwards and it won't compile: the lambda carries its value, so it must stay put.
A lambda that decides the order
Student liam = new Student("Liam", 92);
Student sophia = new Student("Sophia", 88);
Student kenji = new Student("Kenji", 75);
Student mira = new Student("Mira", 88);
List<Student> ranks =
new ArrayList<>(List.of(liam, sophia, kenji, mira));
// compare(a, b) as one lambda: highest marks first
Comparator<Student> byMarks =
(a, b) -> Integer.compare(b.marks(), a.marks());
Comparator<Student> byName =
(a, b) -> a.name().compareTo(b.name());
System.out.println("Kenji vs Mira: " + byMarks.compare(kenji, mira));
System.out.println("Sophia vs Mira: " + byMarks.compare(sophia, mira));
Collections.sort(ranks, byMarks);
System.out.println("By marks: " + ranks);
// Sophia and Mira tie on 88: break the tie by name
Collections.sort(ranks, byMarks.thenComparing(byName));
System.out.println("Tie A-Z: " + ranks);
Kenji vs Mira: 1
Sophia vs Mira: 0
By marks: [Liam 92, Sophia 88, Mira 88, Kenji 75]
Tie A-Z: [Liam 92, Mira 88, Sophia 88, Kenji 75]
Comparator has one method, compare, so each comparator is one lambda instead of the anonymous class from Comparable and Comparator. Kenji vs Mira is positive, so Mira goes first. Sophia vs Mira is a tie, so sorting by marks keeps their old order, and thenComparing(byName) puts Mira first. Student here is a record with a short toString.
Recap
A lambda is the parameters, an arrow and the work. It fits wherever a method expects a functional interface such as Runnable or Comparator, and anything it uses from outside must stay effectively final. Java ships many ready-made ones; see built-in functional interfaces.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
Four ready-made sockets for lambdas: Predicate tests 20 >= 18, Function turns 5 into 15, Consumer prints Hello, Priya, Supplier hands back Monday. Then isPositive.and(isEven), isEven.negate() and multiply.andThen(addFive), which turns 3 and 4 into 17.
Java Optional: Saying Maybe Without null
A phone book returns null for Omar and the next .length() crashes. Optional.ofNullable gives a box instead: Optional[555-1234] or Optional.empty. orElse hands over "no number", ifPresent runs only for Asha, and map adds +1 only when there's a number.
Java Streams I: filter, map and reduce
Picture a conveyor belt: 4, 7, 2, 9, 5 ride through filter(n -> n > 4) and map(n -> n * 10) and come out as [70, 90, 50]. Then sorted and count on exam scores, and reduce folding a cart of 499, 1299, 250 and 799 into a 2847 bill.
Java Streams II: Collectors, groupingBy and flatMap
Six sales feed every example. toList and joining give [Emma, Jake, Sofia] and "North / South / West", groupingBy with counting and summingInt gives a count and a total per region, flatMap pours three orders' items into one list, and mapToInt sums 5400.
