java8 Optional正确使用姿势
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); } }
本文来自博客园,作者:hjzqyx,转载请注明原文链接:https://www.cnblogs.com/hujunzheng/p/7299572.html