本文共 1609 字,大约阅读时间需要 5 分钟。
import lombok.Data;import lombok.EqualsAndHashCode;import lombok.ToString;import org.apache.commons.lang3.StringUtils;import java.util.Optional;@Data@EqualsAndHashCode(exclude={"self"})@ToString(callSuper=true, exclude="self")public class PersonDto { private Integer id; private String name; private String password; private Double self; public boolean validateName1() { return StringUtils.equals("hjz", name); } public static boolean validateName2(String name) { return StringUtils.equals("hjz", name); } public static void main(String[] args) { PersonDto personDto = new PersonDto(); personDto.setName("hjz");// String name = Optional.ofNullable(personDto)// .map(obj -> obj.getName())// .filter(StringUtils::isNotEmpty)// .orElseThrow(()->new IllegalArgumentException("The value of param personDto isn't available."));// String name = Optional.ofNullable(personDto)// .map(obj -> obj.getName())// .filter(PersonDto::validateName2)// .orElseThrow(()->new IllegalArgumentException("The value of param personDto isn't available.")); String name = Optional.ofNullable(personDto) .filter(PersonDto::validateName1) .map(obj -> obj.getName()) .orElseThrow(()->new IllegalArgumentException("The value of param personDto isn't available.")); System.out.println(name); }}