Lambda表达式

基本使用

Arrays.asList( "a", "b", "d" ).forEach( e -> System.out.println( e ) );

Arrays.asList( "a", "b", "d" ).forEach( ( String e ) -> System.out.println( e ) );

Arrays.asList( "a", "b", "d" ).forEach( e -> {
    System.out.print( e );
    System.out.print( e );
});


Lambda可以引用类的成员变量与局部变量(如果这些变量不是final的话,它们会被隐含的转为final,这样效率更高)

final String separator = ",";
Arrays.asList( "a", "b", "d" ).forEach( e -> System.out.print( e + separator ) );


如果lambda的函数体只有一行的话,那么没有必要显式使用return语句。

函数式接口

函数式接口(只包含一个抽象方法的接口,称为函数式接口)中Lambda表达式:相当于匿名内部类的效果。

    //Java8之前
    execute(new Runnable() {
        @Override
        public void run() {
            System.out.println("run");
        }
    });
 
    //使用Lambda表达式
    execute(() -> System.out.println("run"));


 	public interface Runnable { void run(); }
    
 	public interface Callable<V> { V call() throws Exception; }
    
 	public interface Comparator<T> { int compare(T o1, T o2); boolean equals(Object obj); }

	注意最后这个Comparator接口。它里面声明了两个方法,貌似不符合函数接口的定义,但它的确是函数接口。
	这是因为equals方法是Object类的,所有的接口都会声明Object类的public方法——虽然大多是隐式的。
	所以,Comparator显式的声明了equals不影响它依然是个函数接口。

方法引用

方法引用(Lambda表达式的更简洁的一种表达形式,使用::操作符):
	Function<String, Integer> stringToInteger = (String s) -> Integer.parseInt(s);
	等同于
	Function<String, Integer> stringToInteger = Integer::parseInt;
	stringToInteger.apply("12");

排序

Comparator<Students> com = (o1,o2) -> o1.getAge().compareTo(o2.getAge())
Arrays.sort(stu,com);
Comparator.comparing(User::getName)	//对字符串排序
Comparator.comparingInt(User::getAge)	//对int排序
Comparator.comparing( Person::getName,(o1,o2) -> Integer.compare( o1.length(),o2.length() ) )	//对name长度排序
Comparator.comparingInt( o -> o.getName().length() )	//对name长度排序

Arrays.asList( "a", "b", "d" ).sort( ( e1, e2 ) -> e1.compareTo( e2 ) );
原文地址:https://www.cnblogs.com/loveer/p/11808211.html