Commit 1cd4c872 authored by Trisha Gee's avatar Trisha Gee
Browse files

Lambda examples

parent 5554a6da
Loading
Loading
Loading
Loading
+54 −1
Changes for src/main/java/ch10c/HelloLambda.java: 54 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -2,11 +2,14 @@ package ch10c;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class HelloLambda {
  public static void main(String[] args) {
    lambdaAsBehaviour();
    mandatoryTypes();
  }

  static void helloLambda() {
@@ -32,4 +35,54 @@ public class HelloLambda {
                                 .limit(4)
                                 .collect(Collectors.toList());
  }

  static void longLambda() {
    List<String> strings = new ArrayList<>(List.of("I", "am", "a", "list", "of", "Strings"));

    List<String> result = strings.stream()
                                 .sorted(
                                         (String s1, String s2) -> {
                                           return s1.compareToIgnoreCase(s2);
                                         })
                                 .collect(Collectors.toList());
    System.out.println("result = " + result);
  }

  static void multilineLambda() {
    List<String> strings = new ArrayList<>(List.of("I", "am", "a", "list", "of", "Strings"));
    Stream<String> sorted = strings.stream().sorted(
            (str1, str2) -> {
              int l1 = str1.length();
              int l2 = str2.length();
              return l2 - l1;
            });

    List<String> result = sorted.collect(Collectors.toList());
    System.out.println("result = " + result);
  }

  static void noReturn() {
    List<String> strings = new ArrayList<>(List.of("I", "am", "a", "list", "of", "Strings"));
    strings.forEach(
            (String str) -> {
              String output = "str = " + str;
              System.out.println(output);
            }
    );
  }

  static void mandatoryTypes() {
    // if you remove String from the param here, the compiler doesn't know which method you want
    overloadedMethod((String str) -> System.out.println(str));
  }

  private static void overloadedMethod(Consumer<String> consumer) {
    consumer.accept("Something");
  }

  private static void overloadedMethod(Function<Integer, Integer> function) {
    function.apply(1);
  }


}