1、得到流:Arrays.asStream()
2、中间操作
3、终端操作:
https://baize.rnd.huawei.com/guide-book/java/VolumeBase/tools/chgtsnoOptionalIfElseThrow
// 简单检查 Objects.requireNonNull(t); // 带Message的检查:若失败则抛java.lang.NullPointerException: Param t should not be null Objects.requireNonNull(t, "Param t should not be null"); // 断言+赋值,一步到位 this.id = Objects.requireNonNull(idVal); // 带Message的断言:若失败则抛java.lang.NullPointerException: Param t should not be null this.id = Objects.requireNonNull(idVal, "Param idVal should not be null");
this.name = Optional.ofNullable(inputName).orElse("SOME_DEFAULT_NAME"); 基于Guava // 简单断言 Preconditions.checkArgument(param.endsWith("abc")); // 带Message的断言 Preconditions.checkArgument(param.endsWith("abc"), "Para doesn't end with abc"); // 带Message format的断言 Preconditions.checkArgument(param.endsWith("abc"), "Para %s doesn't end with %s", param, "abc");
void setId(@NonNull String id) { if (id.contains("xxx")) { // ... } }
// info不为null才执行,null场景并不报错 Optional.ofNullable(info).ifPresent(System.out::println);
Optional.ofNullable(result) .map(DResult::getDevice) .map(Device::getGroup) .map(Group::getId) .ifPresent(Dummy::doSomething); 对比: // 多级if判空 if (result != null && result.getDevice() != null && result.getDevice().getGroup() != null) { String groupId = result.getDevice().getGroup().getId(); if (groupId != null) { Dummy.doSomething(groupId); } } // 对比,有返回值场景:返回 result.getDevice().getGroup().getName() 或 unknown return Optional.ofNullable(result) .map(DResult::getDevice) .map(Device::getGroup) .map(Group::getName) .orElse("Unknown"); return Optional.ofNullable(device).map(Device::getName).orElse("Unknown"); return Optional.ofNullable(device).map(Device::getName).orElseGet(this::getDefaultName); return Optional.ofNullable(result).map(DResult::getDevice).orElseThrow(() -> new DummyException("No device")); // 获得device对应的Group Optional.ofNullable(device).map(dvc -> dvc.getGroup()).ifPresent(grp -> Dummy.doSomething(grp)); // FunctionalInterface部分的内容,推荐使用方法引用方式,提升编码简洁度 Optional.ofNullable(device).map(Device::getGroup).ifPresent(Dummy::doSomething); Optional.ofNullable(device) .filter(d -> d.getName() != null) // 如果device.getName为null,则提前结束 .ifPresent(Dummy::doSomething);