实体类
package po ;
import lombok. AllArgsConstructor ;
import lombok. Data ;
import lombok. NoArgsConstructor ;
import java. io. Serializable ;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student implements Serializable {
private String name;
private Address address;
}
package po ;
import lombok. AllArgsConstructor ;
import lombok. Data ;
import lombok. NoArgsConstructor ;
@AllArgsConstructor
@Data
@NoArgsConstructor
public class Address {
private String city;
}
Optional对非空对象的处理
满足过滤条件返回的值
package com. demo ;
import po. Address ;
import po. Student ;
import java. util. Optional ;
public class TestCase3 {
public static void main ( String [ ] args) {
Student student = new Student ( "张三" , new Address ( "香港" ) ) ;
Student student1 = Optional . ofNullable ( student)
. filter ( s -> "张三1" . equals ( s. getName ( ) ) )
. orElseGet ( ( ) -> new Student ( "李四" , new Address ( "北京" ) ) ) ;
System . out. println ( student1) ;
}
}
不满足条件返回的值
package com. demo ;
import po. Address ;
import po. Student ;
import java. util. Optional ;
public class TestCase3 {
public static void main ( String [ ] args) {
Student student = new Student ( "张三" , new Address ( "香港" ) ) ;
Student student1 = Optional . ofNullable ( student)
. filter ( s -> "张三" . equals ( s. getName ( ) ) )
. orElseGet ( ( ) -> new Student ( "李四" , new Address ( "北京" ) ) ) ;
System . out. println ( student1) ;
}
}