更多的新特性可以参阅官网:What’s New in JDK 8
Lambda 表达式,也可称为闭包,它是推动 Java 8 发布的最重要新特性。
Lambda 允许把函数作为一个方法的参数(函数作为参数传递进方法中)。
使用 Lambda 表达式可以使代码变的更加简洁紧凑。
@Test
public void test1() {
//普通方式
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("执行方法");
}
};
r.run();
System.out.println("*******************************************");
//lambda表达式方式
Runnable r2 = () -> System.out.println("执行了方法");
r2.run();
}
@FunctionalInterface
public interface Runnable {
/**
* When an object implementing interface Runnable
is used
* to create a thread, starting the thread causes the object's
* run
method to be called in that separately executing
* thread.
*
* The general contract of the method run
is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
像这种函数式接口(@FunctionalInterface),用lambda表达式写是最方便的,不需要再写匿名内部类,书写方便,可读性也可以。
例子一中,是没有形参的,就可以直接用()。如果有参数,就在()中加参数,参数可以写类型,也可以不写(会根据类型推断)
@Test
public void test2() {
Comparator<Integer> c = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(02);
}
};
System.out.println(c.compare(1, 10));
System.out.println("**************************");
Comparator<Integer> comparator = (o1, o2) -> o1.compareTo(o2);
Comparator<Integer> comparator2 = (o1, o2) -> Integer.compare(o1, o2);
System.out.println(comparator.compare(10, 1));
System.out.println(comparator2.compare(10, 100));
}
1.消费型 Consumer void accept(T t)
2.供给型 Supplier T get()
3.函数型 Function
4.断定型 Predicate boolean test(T t)
@Test
public void test3() {
//1.消费型 Consumer void accept(T t)
Consumer<String> c = s -> System.out.println(s);
c.accept("hello world");
}
//输出结果 hello world
有输入,返回值为void
@Test
public void test4() {
//2.供给型 Supplier T get()
Supplier<String> supplier = () -> "nihao ";
System.out.println(supplier.get());
}
//输出 nihao
没有输入,有返回值
@Test
public void test5() {
//3.函数型 Function R apply(T t)
Function<String, Integer> function = s -> s.length();
System.out.println(function.apply("hello world"));
}
// 11
T为形参类型,R为返回值类型
@Test
public void test6() {
//4.断定型 Predicate boolean test(T t)
Predicate<Integer> predicate = integer -> integer >= 100;
System.out.println(predicate.test(99));
//false
}
T为形参类型, 返回值为boolean型
Lambda给java注入的新鲜血液,可以有效的提高开发,减少代码量,试代码看着整洁很值得学习