Lambda study summary

By | June 11, 2016
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

Below code is a basic way to self-define a lambda. Basically, it requires:
1. a interface with only one function
2. a method which has the interface as parameter, and in the method, it will call the function in that interface implementation.

public static void simpleWay() {
    Math add = new Math() {
        @Override
        public int operate(int a, int b) {
            return a + b;
        }
    };
    Math sub = new Math() {
        public int operate(int a, int b) {
            return a - b;
        }
    };
    System.out.println(MathOperation(1, 2, add));
    System.out.println(MathOperation(1, 2, sub));
}

public static void lambdaWay() {
    Math add = (int a, int b) -> a + b;
    Math sub = (int a, int b) -> a - b;
    System.out.println(MathOperation(1, 2, add));
    System.out.println(MathOperation(1, 2, sub));
}

/**
 * MathOperation and Math are the core for defining lambda expression.
 * An operation interface and a function which uses interface.do() to return something.
 */

public static int MathOperation (int a, int b, Math math) {
    return math.operate(a, b);
}

interface Math {
    public int operate(int a, int b);
}

After that, below are some useful lambda expression in Java 8.

public static void forEachCase() {
    List<Integer> list = new ArrayList<>();
    list.add(1);
    list.add(2);
    list.add(3);
    list.forEach(i -> System.out.println(i));
}

public static void removeIf() {
    List<Integer> list = new ArrayList<>();
    list.add(1);
    list.add(2);
    list.add(3);
    list.removeIf(i -> i == 2); // if only has one element, doesn't has to be (Integer i) -> i == 2 ....  Could be i -> i == 2
    System.out.println(list);
}

public static void replaceAll() {
    List<Integer> list = new ArrayList<>();
    list.add(1);
    list.add(2);
    list.add(3);
    list.replaceAll(i -> -i);
    System.out.println(list);
}

public static void sortCase1() {
    List<Integer> list = new ArrayList<>();
    list.add(3);
    list.add(2);
    list.add(1);
    list.add(4);
    Collections.sort(list, (i1, i2) -> i1 - i2);
    System.out.println(list);
}

public static void sortCase2() {
    List<Integer> list = new ArrayList<>();
    list.add(3);
    list.add(2);
    list.add(1);
    list.add(4);
    list.sort((i1, i2) -> i1 - i2);
    System.out.println(list);
}

public static void threadCase() {
    Runnable r1 = () -> {
        try {
            for (int i = 0; i < 10; i++) {
                System.out.println(i);
                Thread.sleep(1000);
            }
        } catch (Exception e) {}
    };
    new Thread(r1).start();
}