【Java8】Stream&Optional

2022/8/2 14:23:58

本文主要是介绍【Java8】Stream&Optional,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

§ 一、Stream

image.png

1、得到流:Arrays.asStream()

2、中间操作

3、终端操作:

§ 二、Optional

https://baize.rnd.huawei.com/guide-book/java/VolumeBase/tools/chgtsnoOptionalIfElseThrow

  • 非空断言:JDK的Objects.requireNonNull
// 简单检查
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");
  • lombok.NonNull、javax.annotation.Nonnull和javax.validation.constraints.NotNull
  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的多次map,可以依次逐级get对象的子对象,一定程度上替代多级if判空。
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);

 



这篇关于【Java8】Stream&Optional的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程