我有以下课程“商店”: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 的流类或另一种方法,我想获得工作日的平面列表,包括 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的流类)或其他预定义的方法来做到这一点?先感谢您 :)
1 回答
白衣染霜花
TA贡献1796条经验 获得超10个赞
通过使用flatMap你可以实现这一点,首先流式传输stores列表,然后通过将每个映射到flatMap流中。List<DayOfWeek>DayOfWeekOtherType
//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());
添加回答
举报
0/150
提交
取消