@Test
public void optionalTest(){
Peo peo = new Peo("weijie", 18);
Optional<Peo> _of = Optional.of(peo);
Optional<Peo> _ofNullable = Optional.ofNullable(null);
System.out.println("_of: " + _of.isPresent());
System.out.println("_ofNullable: " + _ofNullable.isPresent());
Peo _orElse = _ofNullable.orElse(peo);
System.out.println("_orElse: " + _orElse);
Peo _orElseGet = _ofNullable.orElseGet(() -> peo);
System.out.println("_orElseGet:" +_orElseGet);
Peo _orElseThrow = _ofNullable.orElseThrow(() -> new IllegalArgumentException());
System.out.println("orElseThrow: " + _orElseThrow);
Optional<Peo> _filter = _of.filter(p -> p.age == 18);
System.out.println("_filter: " + _filter.isPresent());
Optional<Peo> _filter2 = _of.filter(p -> p.age == 16);
System.out.println("_filter: " + _filter2.isPresent());
Optional<Integer> _map = _of.map(Peo::getAge);
boolean _age = _map.filter(age -> age >= 15).filter(age -> age <= 24).isPresent();
System.out.println("_age: " + _age);
People people = new People("weijie", 25);
Optional<Integer> _flatMap = Optional.ofNullable(people).flatMap(People::getAge);
System.out.println("_flatMap: " + _flatMap.get());
}
class Peo{
String name;
Integer age;
public Peo(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Peo{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
class People{
String name;
Integer age;
public People(String name, Integer age) {
this.name = name;
this.age = age;
}
public Optional<String> getName() {
return Optional.ofNullable(name);
}
public void setName(String name) {
this.name = name;
}
public Optional<Integer> getAge() {
return Optional.ofNullable(age);
}
public void setAge(Integer age) {
this.age = age;
}
}