[英]Java 8: Recursive stream map
In my Library
class there is a Set<Library> items
field.在我的Library
类中有一个Set<Library> items
字段。 Hence there in the LibraryDTO
I have Set<LibraryDTO> items
.因此在LibraryDTO
我有Set<LibraryDTO> items
。 When I build a Library
from the LibraryDTO
, I realized that I will enter an infinite loop in converting the DTO to an entity in this items field, example:当我从LibraryDTO
构建一个Library
,我意识到在将 DTO 转换为该项目字段中的实体时,我将进入一个无限循环,例如:
private Library buildLibraryFromLibraryDTO(LibraryDTO libraryDTO) {
return Library.builder()
.items(libraryDTO.getItems().stream().map(library -> Library.builder()
.items(library.getItems().stream().map ... repeats the same DTO to entity conversion process from the above level)
.build()).collect(Collectors.toSet()))
.build();
}
I thought about making a recursive method going through the items stream but I'm having difficulties with logic.我想过在项目流中使用递归方法,但我在逻辑上遇到了困难。 How could I do it?我怎么能做到? I researched and saw some examples of recursion with stream but was unable to replicate for my case.我研究并看到了一些使用流递归的例子,但无法复制我的案例。 Thank you谢谢
You need to use a base case when you don't need to call recursively to avoid an infinite loop.当您不需要递归调用以避免无限循环时,您需要使用基本情况。 Means when libraryDTO.getItems()
is null then don't call again.意味着当libraryDTO.getItems()
为 null 时不再调用。
You can use ternary operator to check if libraryDTO.getItems()
is not null then call buildLibraryFromLibraryDTO
for every item else null.您可以使用三元运算符来检查libraryDTO.getItems()
是否不为空,然后为其他为空的每个项目调用buildLibraryFromLibraryDTO
。
private Library buildLibraryFromLibraryDTO(LibraryDTO libraryDTO) {
return Library.builder()
.items(libraryDTO.getItems() != null
? libraryDTO.getItems()
.stream()
.map(library -> buildLibraryFromLibraryDTO(library))
.collect(Collectors.toSet())
: null)
.build();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.