Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Lambdas and Streams

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Lambdas and Streams

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.

ParametersBracketsExample
nonerequired: ()() -> "Small step every day"
oneoptionalname -> "Hello, " + name
two or morerequired(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
main calls runJob with the name "class report" and a lambda that uses course and students. Inside runJob, START prints, job.run() runs the lambda which prints Java Foundation: 3 students, then DONE prints. The lambda carries the value of course, so course must stay effectively final. main () -> ... course, students.size() runJob(name, job) START class report job.run(): the note runs here DONE class report course = "Spring Boot" afterwards: won't compile
A lambda is code as a value: it rides the call and runs inside the method.

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.

Keep going in Java · 60 of 79

Previous
Java Generic Methods, Bounded Types and Wildcards
Next post
Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • Six lines fall away
  • No parameters, one, or two
  • Hand the code to a method
  • A lambda that decides the order
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.