java语言
Lambda 表达式 (可以封装一种行为,并把行为传给其他代码),有以下几种形式
步骤 1 定义行为的接口 2 Lambda 表达式实现接口 Lambda 表达式规范 (变量类型1 变量1,变量类型2 变量2) -> {代码;}
public class Main {
public static void main ( String[ ] args) {
Intoperation io = ( int x, int y) - > {
System. out. println ( x + y) ;
return x + y;
} ;
}
}
interface Intoperation {
int operate ( int x, int y) ;
}
方法引用
有时候某种行为是已经定义好的,不需要我们再次定义,只需我们引用就行。而行为就是面向对象的方法,所有对行为的引用就是对方法的引用。 构造器,类::静态方法,类::实例方法
public class Main {
public static void main ( String[ ] args) {
Supplier< Person> supplier = Person: : new ;
Function< String, Person> function = ( String name) - > new Person ( name) ;
List< String> list = Arrays. asList ( "1" , "2" , "3" ) ;
list. forEach ( System. out: : println) ;
List< Person> list1 = Arrays. asList ( supplier. get ( ) ) ;
list1. forEach ( Person: : printName) ;
}
}
class Person {
private String name = "iamroy" ;
public Person ( String name) {
this . name = name;
}
public Person ( ) {
}
public void printName ( ) {
System. out. println ( name) ;
}
}
默认方法 (如果要修改已有接口,就要修改实现接口的全部类,这是不可能的),为了在已有接口中添加方法。如 java 8 之前的集合框架没有 foreach 方法,可以在接口中加入默认方法。
public interface Iterable < T>
{
Iterator< T> iterator ( ) ;
}
public interface Iterable < T> {
Iterator< T> iterator ( ) ;
default void forEach ( Consumer< ? super T> action) {
Objects. requireNonNull ( action) ;
for ( T t : this ) {
action. accept ( t) ;
}
}
default Spliterator< T> spliterator ( ) {
return Spliterators. spliteratorUnknownSize ( iterator ( ) , 0 ) ;
}
}
重复注解 如果想在一个地方使用同一个注解多次,可以使用重复注解
步骤 1、定义重复注解,注解上有@Repeatable 2、定义容器
@Acess ( role = "a" )
@Acess ( role = "b" )
public class Main {
public static void main ( String[ ] args) {
Acess[ ] acesses = Main. class . getAnnotationsByType ( Acess. class ) ;
System. out. println ( acesses. length) ;
}
}
@Repeatable ( Acesses. class )
@Retention ( RetentionPolicy. RUNTIME)
@interface Acess {
String role ( ) ;
}
@Retention ( RetentionPolicy. RUNTIME)
@interface Acesses {
Acess[ ] value ( ) ;
}
stream 流
lambda表达式的一种运用,就是对集合进行几种操作,操作用lambda表示,操作有sort,filter,map,limit,统计(sum,average),collect,reduce public static void main ( String[ ] args) {
List< Integer> list = Arrays. asList ( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ) ;
Map< Integer, Integer> collect = list. stream ( ) . sorted ( ( a, b) - > a - b) . map ( i - > i * i) . filter ( i - > i % 2 == 0 ) . limit ( 5 ) . collect ( Collectors. toMap ( i - > i, i - > i * i) ) ;
}
Optional 类,感觉这个类的对象就是一个引用,但是这个引用还有很多方法
public static void main ( String[ ] args) {
Integer a = null;
Optional< Integer> b = Optional. ofNullable ( null) ;
System. out. println ( a. intValue ( ) ) ;
System. out. println ( b. isPresent ( ) ) ;
}
日期时间 API
LocalDate, LocalTime,ZonedDateTime
public static void main ( String[ ] args) {
LocalDate localDate = LocalDate. of ( 2019 , 2 , 28 ) ;
LocalDate localDate1 = localDate. plusDays ( 1 ) ;
System. out. println ( localDate1) ;
}