编程语言
首页 > 编程语言> > 【Java8】Stream&Optional

【Java8】Stream&Optional

作者:互联网

§ 一、Stream

image.png

1、得到流:Arrays.asStream()

2、中间操作

3、终端操作:

§ 二、Optional

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");
  1. @NonNull用在强制入参非空、属性非空的场景下,编译时会生成空指针检查的代码,如果不满足,则会抛出NullPointerException。
  2. @Nonnull用在返回结果不为空的场景,主要由IDE识别并给出告警提示。
  3. @NotNull主要用在Validator校验场景下,限制参数非空,如果不满足,则校验失败。
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);

 

标签:map,ofNullable,Stream,result,device,null,Optional,Java8
来源: https://www.cnblogs.com/clarino/p/16541713.html