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();
}
}
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]);
}
}
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.