gpt4 book ai didi

java - orElseGet 在 Optional> 的情况下如何工作

转载 作者:行者123 更新时间:2023-12-05 00:52:28 25 4
gpt4 key购买 nike

我有一个可选的类列表,即:Optional<List<MyEntity>> opListEntity

我需要映射所有 MyEntityMyEntityDto当可选存在时。如果 Optional 为空,我将返回一个空的 ArrayList


方法 1(非功能性):

注意:myEntityMapper是映射器类的对象,它映射 MyEntityMyEntityDto .

List<MyEntityDto> res;
if (opListEntity.isPresent()) {
res = opListEntity.get().stream()
.map(myEntityMapper::entityToDto)
.collect(Collectors.toList());
} else {
res = new ArrayList<>();
}

这种方法很好,但 IntelliJ 建议将其转换为函数式表达式。我让 IntelliJ 进行转换,这就是我得到的:

方法二(函数表达式):

List<MyEntityDto> res = opListEntity.map(myEntities -> myEntities.stream()
.map(myEntityMapper::entityToDto)
.collect(Collectors.toList()))
.orElseGet(ArrayList::new);

我不明白的是,在方法 2 @ line 1 中,为什么会有 map ?

让我再解释一下。见第三种方法:

方法3:

List<CustomerAddressEntity> myEntities = opListEntity
.orElseGet(ArrayList::new);
List<MyEntityDto> res = myEntities.stream()
.map(myEntityMapper::entityToDto)
.collect(Collectors.toList());

方法 3 工作正常,但如果我尝试将方法 3 转换为方法 4,它就不起作用了。

方法4:

List<MyEntityDto> res = opListEntity.stream()
.map(myEntityMapper::entityToDto)
.collect(Collectors.toList()))
.orElseGet(ArrayList::new);

为什么方法 4 不起作用,而 方法 2 起作用?
mapapproach 2 @ line 1 中做了什么?

最佳答案

我认为如果您将代码缩进一点以使其更容易发现,就会变得很明显:

List<MyEntityDto> res = opListEntity // Optional<List<MyEntity>>
.map(
myEntities -> myEntities.stream() // Stream<MyEntity>
.map(myEntityMapper::entityToDto) // Stream<MyEntityDto>
.collect(Collectors.toList()) // List<MyEntityDto>
)
.orElseGet(ArrayList::new); // List<MyEntityDto>

那是Optional (如果存在)映射到将包含列表转换为流、映射元素并构建集合的结果,或者(如果为空)映射到新的空列表。

在您的第 4 种方法中 opListEntityOptional<List<MyEntity>> 类型.现在它取决于您使用的 JDK 版本。在 JDK8 Optional没有stream()方法。

List<MyEntityDto> res = opListEntity.stream() // there is no such method in JDK8
...

从JDK9开始有一个stream()方法,但它当然会返回 Stream<List<MyEntity>>因为这是 Optional 的类型.但是要使映射起作用,您需要 Stream<MyEntity> .为此,您可以使用 flatMap 映射返回的流。方法:

List<MyEntityDto> res = opListEntity.stream() // Stream<List<MyEntity>>
.flatMap(List::stream) // Stream<MyEntity>
.map(myEntityMapper::entityToDto)
...

关于java - orElseGet 在 Optional<List<Entity>> 的情况下如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69981085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com