Java8 lamada 表达式

Java8 lamada 表达式

参考资料出自 http://www.runoob.com/java/java8-lambda-expressions.html

/**
 * Created by Allen on 2018/3/27.
 */
public class TestLamada {

    public static void main(String[] args) {
        TestLamada tester = new TestLamada();

        /**
         *类型声明
         */
        MathOperation addition = (int a, int b) -> a + b;
        /**
         * 不用类型声明
         */
        MathOperation subtraction = (a, b) -> a + b;

        /**
         * 大括号中的返回语句
         */
        MathOperation multiplication = (a, b) -> {
            return a * b;
        };
        MathOperation division = (int a, int b) -> a / b;

        System.out.println("args = [" + tester.operate(10, 5, addition) + "]");

        System.out.println("args = [" + tester.operate(10, 5, subtraction) + "]");
        System.out.println("args = [" + tester.operate(10, 5, multiplication) + "]");
        System.out.println("args = [" + tester.operate(10, 5, division) + "]");
        GreetingService greetService =message-> System.out.println("message = " + message);
        GreetingService greetingService2 =(message)-> System.out.println("message = " + message);
        System.out.println("greetingService2 = " + greetingService2);
        greetService.sayMessage("Runoob");
        greetingService2.sayMessage("Google");

    }


    interface MathOperation {
        int operation(int a, int b);
    }

    interface GreetingService {
        void sayMessage(String message);
    }

    private int operate(int a, int b, MathOperation mathOperation) {
        return mathOperation.operation(a, b);
    }
}

stream 结合lamada

public class Stream {
    public static void main(String[] args) {
        List names = new ArrayList<>();
        names.add("Jack");
        names.add("Allen");
        /**
         * lamada 第一种写法
         */
        Collections.sort(names, (o1, o2) -> o1.compareTo(o2));

        /**
         * lamada 第二种写法
         */
        Collections.sort(names, String::compareTo);
        /**
         * lamada stream写法
         */
        names.stream().map(s -> s.toLowerCase()).collect(Collectors.toList());
        /**
         * lamada 写法
         */
        names.stream().map(String::toLowerCase).collect(Collectors.toList());


    }
}

你可能感兴趣的:(Java8 lamada 表达式)