[英]Aggregate objects into collections in Java using streams
我有一個結構對象列表
public class SimpleObject {
private TypeEnum type;
private String propA;
private Integer propB;
private String propC;
}
我想“打包”到以下對象中
public class ComplexObject {
private TypeEnum type;
private List<SimpleObject> simpleObjects;
}
基於類型枚舉。
換句話說,我想創建一種聚合,它將保存每個包含特定type
SimpleObject
。 我想用 Java 8 流來做,但我不知道怎么做。
因此,假設我正在獲取SimpleObject
的列表,例如
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class DataService {
private final DataRepository dataRepo;
public void getPackedData() {
dataRepo.getSimpleObjects().stream()...
}
}
接下來的步驟應該如何? 預先感謝您的任何幫助
我在 Spring Boot 中使用 Java 14
您可以使用Collectors.groupingBy
按返回Map<TypeEnum, List<SimpleObject>>
的type
進行分組。 然后再次流過地圖的條目集以轉換為List<ComplexObject>
List<ComplexObject> res =
dataRepo.getSimpleObjects()
.stream()
.collect(Collectors.groupingBy(SimpleObject::getType)) //Map<TypeEnum, List<SimpleObject>>
.entrySet()
.stream()
.map(e -> new ComplexObject(e.getKey(), e.getValue())) // ...Stream<ComplexObject>
.collect(Collectors.toList());
您可以使用Collectors.groupingBy
實現這一點,並使用Collectors.collectingAndThen
將條目進一步轉換為對象列表。
List<SimpleObject> list = ...
List<ComplexObject> map = list.stream()
.collect(Collectors.collectingAndThen(
Collectors.groupingBy(SimpleObject::getType), // group by TypeEnum
map -> map.entrySet() // map entries to ..
.stream()
.map(e -> new ComplexObject(e.getKey(), e.getValue())) // .. ComplexObject
.collect(Collectors.toList()))); // .. to List
我目前不知道另一種解決方案,只要 Stream API 在處理字典結構時不友好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.