java8的常用的新特征
一、Java 8 对接口做了进一步的增强。(默认方法和静态方法)
a. 在接口中可以添加使用 default 关键字修饰的非抽象方法。即:默认方法(或扩展方法不用被实现)如:comparator接口。Iterable接口中的forEach默认方法。
b. 接口里可以声明静态方法,并且可以实现。如:comparator接口。Collections.sort(), max(), min() 等方法;
Java8内部类访问外部变量不需要加final修饰。
二、Java8新增list.forEach遍历(Lambda表达表达式,代替匿名内部类)
遍历方式:
1
2
3
4
5
6
|
list.forEach( new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
}); |
1
2
3
4
5
|
Lambda表达式:
list.forEach(s ->{ System.out.println(s);
}
);
|
<wiz_tmp_tag class=”wiz-block-scroll”>
函数作为参数传递进方法中。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
TestJava8 tester = new TestJava8();
// 类型声明
MathOperation addition = ( int a, int b) -> a + b;
// 不用类型声明
MathOperation subtraction = (a, b) -> a - b;
// 大括号中的返回语句
MathOperation multiplication = ( int a, int b) -> { return a * b; };
// 没有大括号及返回语句
MathOperation division = ( int a, int b) -> a / b;
System.out.println( "10 + 5 = " + tester.operate( 10 , 5 , addition));
System.out.println( "10 - 5 = " + tester.operate( 10 , 5 , subtraction));
System.out.println( "10 x 5 = " + tester.operate( 10 , 5 , multiplication));
System.out.println( "10 / 5 = " + tester.operate( 10 , 5 , division));
}
interface MathOperation {
int operation( int a, int b);
}
private int operate( int a, int b, MathOperation mathOperation){ //接口作为方法的参数,传对应的实现类,lambd表达式代替了匿名类
return mathOperation.operation(a, b);
}
|
三、可以使用重复注解
1
2
3
4
|
@Filter ( "filter1" )
@Filter ( "filter2" )
public interface Filterable {
} |
四、新的Date/Time ApI
LocalDate,LocalTime,Clock类;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
final Clock clock = Clock.systemUTC();
System.out.println( clock.instant() );
System.out.println( clock.millis());
// Get the local date and local time
final LocalDate date = LocalDate.now();
final LocalDate dateFromClock = LocalDate.now( clock );
System.out.println( date );
System.out.println( dateFromClock );
// Get the local date and local time
final LocalTime time = LocalTime.now();
final LocalTime timeFromClock = LocalTime.now( clock );
System.out.println( time );
System.out.println( timeFromClock );
|
五、函数式接口
1、函数式接口(Functional Interface)是只包含一个方法的抽象接口;
2、函数式接口是为Java 8中的lambda而设计的,lambda表达式的方法体其实就是函数接口的实现。
3、@FunctionalInterface注解不是必须的,只要接口只包含一个抽象方法,虚拟机会自动判断该接口为函数式接口,加上后避免添加新方法。
六、方法引用
1、方法引用是lambda表达式的一种简写;
1
2
3
4
5
6
7
|
对象::实例方法 类::静态方法 类::实例方法 类:: new
Arrays.sort(strings, String::compareToIgnoreCase); // 等价于 Arrays.sort(strings, (s1, s2) -> s1.compareToIgnoreCase(s2)); |