- Basic Example:
() -> System.out.println("Hello, Lambda!");
- Lambda expression with no parameters, printing a message.
- Single Parameter:
- Lambda with a single parameter, returning the square.
- Multiple Parameters:
- Lambda with multiple parameters, returning their sum.
- Functional Interface:
Comparator<String> comparator = (s1, s2) -> s1.compareTo(s2);
- Lambda for a
Comparator
functional interface to compare strings.
- ForEach in List:
List<Integer> numbers = Arrays.asList(1, 2, 3);
numbers.forEach(n -> System.out.println(n));
- Using lambda with
forEach
for a list.
- Filter in Stream:
List<Integer> evens = numbers.stream().filter(n -> n % 2 == 0).collect(Collectors.toList());
- Lambda used in stream API to filter even numbers.
- Map in Stream:
List<Integer> squared = numbers.stream().map(n -> n * n).collect(Collectors.toList());
- Lambda in stream API to map each element to its square.
- Reduce in Stream:
int sum = numbers.stream().reduce(0, (a, b) -> a + b);
- Lambda used in stream API for reduction.
- Predicate Interface:
Predicate<String> isLong = s -> s.length() > 10;
- Lambda with
Predicate
for checking string length.
- Function Interface:
Function<Integer, Integer> square = x -> x * x;
- Lambda with
Function
interface for squaring.
- Supplier Interface:
Supplier<String> helloSupplier = () -> "Hello, Supplier!";
- Lambda with
Supplier
interface for supplying a constant value.
- Consumer Interface:
Consumer<String> printUpperCase = s -> System.out.println(s.toUpperCase());
- Lambda with
Consumer
interface to print uppercase.
- Method Reference:
List<String> words = Arrays.asList("apple", "orange", "banana");
words.forEach(System.out::println);
- Using method reference to print each element.
- Constructor Reference:
Supplier<List<String>> listSupplier = ArrayList::new;
- Creating an
ArrayList
using constructor reference.
- Runnable Interface:
Runnable runnable = () -> System.out.println("Running!");
- Lambda for the
Runnable
interface.
- Combining Predicates:
Predicate<String> isLongAndStartsWithA = isLong.and(s -> s.startsWith("A"));
- Combining two predicates using
and
.
- Optional:
Optional<String> result = Optional.of("Hello, Optional!");
result.ifPresent(s -> System.out.println(s));
- Using lambda with
Optional
.
- Exception Handling:
IntSupplier divideByZero = () -> 10 / 0;
- Example of unchecked exception handling.
- BiFunction:
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
- Lambda with
BiFunction
for addition.
- Custom Functional Interface:
MyFunctionalInterface concat = (a, b) -> a + b;
- Using a custom functional interface for string concatenation.