Site icon Java Guidance

Java 8 Lamda Expression basic example

Java 8 Lamda Expression Basic example
  1. Basic Example:
    () -> System.out.println("Hello, Lambda!");
    • Lambda expression with no parameters, printing a message.
  2. Single Parameter:
    (x) -> x * x;
    • Lambda with a single parameter, returning the square.
  3. Multiple Parameters:
    (a, b) -> a + b;
    • Lambda with multiple parameters, returning their sum.
  4. Functional Interface:
    Comparator<String> comparator = (s1, s2) -> s1.compareTo(s2);
    • Lambda for a Comparator functional interface to compare strings.
  5. 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.
  6. 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.
  7. 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.
  8. Reduce in Stream:
    int sum = numbers.stream().reduce(0, (a, b) -> a + b);
    • Lambda used in stream API for reduction.
  9. Predicate Interface:
    Predicate<String> isLong = s -> s.length() > 10;
    • Lambda with Predicate for checking string length.
  10. Function Interface:
Function<Integer, Integer> square = x -> x * x;
  1. Supplier Interface:
Supplier<String> helloSupplier = () -> "Hello, Supplier!";
  1. Consumer Interface:
Consumer<String> printUpperCase = s -> System.out.println(s.toUpperCase());
  1. Method Reference:
List<String> words = Arrays.asList("apple", "orange", "banana");
words.forEach(System.out::println);
  1. Constructor Reference:
Supplier<List<String>> listSupplier = ArrayList::new;
  1. Runnable Interface:
Runnable runnable = () -> System.out.println("Running!");
  1. Combining Predicates:
Predicate<String> isLongAndStartsWithA = isLong.and(s -> s.startsWith("A"));
  1. Optional:
Optional<String> result = Optional.of("Hello, Optional!");
result.ifPresent(s -> System.out.println(s));
  1. Exception Handling:
IntSupplier divideByZero = () -> 10 / 0; // Throws ArithmeticException
  1. BiFunction:
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
  1. Custom Functional Interface:
MyFunctionalInterface concat = (a, b) -> a + b;
Exit mobile version