LearnFrenzy
Sign in Take a free test

Java Programming · Topic 21 of 28

Lambda Expressions

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Coding Techniques

Lambda Expressions · Study material

Lambdas with collections and maps

Since Java 8, List and Map have methods that take lambdas: removeIf, replaceAll, sort, forEach, computeIfAbsent, merge and more.

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("asha", "Ravi", "", "meena", "  ", "john"));
        names.removeIf(String::isBlank);                                  // Predicate
        names.replaceAll(n -> Character.toUpperCase(n.charAt(0)) + n.substring(1));   // UnaryOperator
        names.sort((a, b) -> b.compareTo(a));                             // Comparator
        names.forEach(n -> System.out.print(n + " "));                    // Consumer
        System.out.println();

        Map<String, Integer> stock = new TreeMap<>(Map.of("pen", 5, "book", 0, "bag", 12));
        stock.replaceAll((k, v) -> v + 10);                               // BiFunction
        stock.computeIfAbsent("lamp", k -> k.length());                   // Function
        stock.merge("pen", 1, Integer::sum);                              // BinaryOperator
        stock.forEach((k, v) -> System.out.print(k + "=" + v + " "));     // BiConsumer
        System.out.println();
    }
}

Output

Ravi Meena John Asha
bag=22 book=10 lamp=4 pen=16

Higher-order functions and currying

Functions can take and return other functions – useful for configurable behaviour such as discounts, retry policies or validators.

import java.util.function.Function;
import java.util.function.IntBinaryOperator;
import java.util.function.Supplier;

public class Main {
    // A function that RETURNS a function
    static Function<Double, Double> discount(double percent) {
        return price -> price - price * percent / 100;
    }

    // Currying: a two-argument function as a chain of one-argument functions
    static final Function<Integer, Function<Integer, Integer>> MULTIPLY = a -> b -> a * b;

    // A function that TAKES a function
    static int applyTwice(IntBinaryOperator op, int x, int y) { return op.applyAsInt(op.applyAsInt(x, y), y); }

    // Memoising a Supplier: compute once, reuse afterwards
    static <T> Supplier<T> memo(Supplier<T> s) {
        Object[] cache = {null};
        return () -> {
            if (cache[0] == null) cache[0] = s.get();
            @SuppressWarnings("unchecked") T t = (T) cache[0];
            return t;
        };
    }

    public static void main(String[] args) {
        Function<Double, Double> festive = discount(20), clearance = discount(50);
        Function<Integer, Integer> triple = MULTIPLY.apply(3);
        int[] calls = {0};
        Supplier<String> config = memo(() -> { calls[0]++; return "loaded"; });
        config.get(); config.get(); config.get();
        System.out.println(festive.apply(1000.0) + " " + clearance.apply(1000.0) + " " + triple.apply(7) + " " + MULTIPLY.apply(4).apply(5) + " " + applyTwice((a, b) -> a + b, 1, 10) + " " + calls[0]);
    }
}

Output

800.0 500.0 21 20 21 1

Handling checked exceptions in lambdas

// Function.apply cannot throw IOException, so this does not compile:
//   Function<Path, String> read = p -> Files.readString(p);

// 1. Catch inside the lambda and convert to an unchecked exception
Function<Path, String> read = p -> {
    try { return Files.readString(p); }
    catch (IOException e) { throw new UncheckedIOException(e); }
};

// 2. Or define your own functional interface that declares the exception
@FunctionalInterface
interface IOFunction<T, R> { R apply(T t) throws IOException; }
IOFunction<Path, String> reader = Files::readString;    // a method reference fits perfectly

Lambda checklist

  • Keep lambdas short; move longer logic into a named method and use a method reference.
  • Prefer standard functional interfaces before writing your own.
  • Use primitive specialisations (IntPredicate, ToIntFunction…) in numeric code.
  • Do not mutate captured state; return values instead.
  • Name parameters meaningfully (order -> order.total()).
  • Annotate your own single-method interfaces with @FunctionalInterface.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Java Programming

Java is one of the most used languages in the world – for enterprise software, Android apps, banking systems and backend services. This section covers core Java from syntax and data types to OOP, strings, arrays, exceptions, collections and multithreading, with clear explanations and practice questions for every topic.

Why it matters

  • Java is the main language in service-company placement tests and many product companies
  • OOP, String, collections and exception questions appear in nearly every Java interview
  • Strong core Java is the base for Spring Boot, Android and backend development
  • Java questions are common in university exams and certification tests

Who it is for

  • School students (Class 11–12 / ICSE computer applications) learning Java
  • College students (B.Tech, BCA, MCA) preparing for exams, labs and projects
  • Freshers preparing for placements, Java developer roles and technical interviews
  • Developers revising core Java before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Java developer interviews
  • Service company tests
  • University exams
  • Certification exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links