我有以下类“Store”:
public class Store {
private String storeId;
private String storeName;
private List<DayOfWeek> openiningDays;
}
(e.g.:)
{
storeId: 1
storeName: blabla
openingDays: [MONDAY,TUESDAY,...]
}
和“x”商店列表
List<Store> stores = ......
使用java的stream类,或者其他类型的方法, 我想要一份工作日的简单列表, 包括storeName和storeId。
例如:(期望的结果)
[
{
storeId: 1
storeName: blabla
openingDay: MONDAY
},
{
storeId: 2
storeName: blabla
openingDay: SATURDAY
},
{
storeId: 3
storeName: blabla
openingDay: FRIDAY
}
]
我已经找到了一个可能的解决方案, 但我对此并不满意:
List<OtherType> transformed = new List<>();
for (Store store : stores) {
for (DayOfWeek currentDay : openingDays) {
transformed.add(new OtherType(.....));
}
}
有没有可能用“flatMap(..)”之类的东西来做到这一点 (能够使用java的stream类) 或者其他预定义的方法?
提前谢谢你:)
最佳答案
通过使用 flatMap
你可以实现这一点,首先流式传输 stores
列出,然后在 flatMap
中流List<DayOfWeek>
通过映射每个DayOfWeek
至OtherType
.
//Assuming you have constructor in OtherType with three arguments like OtherType(String storeId, String storeName, DayOfWeek day)
List<OtherType> transformed = stores.stream()
.flatMap(store->store.getOpeningDays().stream()
.map(day->new OtherType(store.getStoreId(),store.getStoreName(),day)))
.collect(Collectors.toList());
关于java - 将包含列表的实例映射到 flatMap(使用流),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57294483/