//方法引用
public class LambdaTest2 {
@Test
public void test(){
Consumer<String> consumer = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println("I lived in "+s+" for last year");
}
};
consumer.accept("China");
//lambda
Consumer<String> consumer1 = s -> System.out.println("I lived in "+s+" for last year");
consumer1.accept("USA");
//方法引用 情况一: 对象 :: 实例方法
PrintStream ps = System.out;
Consumer<String> consumer2 =ps::println;
consumer2.accept("Germany");
}
@Test
public void test2(){
Function<Double,Long> function = new Function<Double, Long>() {
@Override
public Long apply(Double aDouble) {
return Math.round(aDouble);
}
};
System.out.println(function.apply(12.5));
//lambda
Function<Double,Long> function1 = (aDouble) -> Math.round(aDouble);
System.out.println(function.apply(13.5));
//方法引用 情况二: 类 :: 静态方法
Function<Double,Long> function2 =Math::round;
System.out.println(function.apply(14.5));
}
@Test
public void test3(){
//原来的写法
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
};
System.out.println(comparator.compare(12,32));
//lambda
Comparator<Integer> comparator1 = (t1,t2) ->t1.compareTo(t2);
System.out.println(comparator1.compare(65,34));
//方法引用 情况三: 类 :: 实例方法
//Comparator<Integer> comparator2 =Integer::compareTo;
Comparator<Integer> comparator2 =Integer::compare;
System.out.println(comparator2.compare(55,65));
}
}