猿问

将包含列表的实例映射到 flatMap(使用流)

我有以下课程“商店”:


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的流类)或其他预定义的方法来做到这一点?


先感谢您 :)


皈依舞
浏览 108回答 1
1回答

白衣染霜花

通过使用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()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .flatMap(store->store.getOpeningDays().stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(day->new OtherType(store.getStoreId(),store.getStoreName(),day)))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());
随时随地看视频慕课网APP

相关分类

Java
我要回答