user8166384 :
i have the following class 'Store':
public class Store {
private String storeId;
private String storeName;
private List<DayOfWeek> openiningDays;
}
(e.g.:)
{
storeId: 1
storeName: blabla
openingDays: [MONDAY,TUESDAY,...]
}
and a list of 'x' Stores
List<Store> stores = ......
Using the stream class of java, or anther kind method, i want to get a flat list of weekdays, including the storeName and storeId.
e.g: (desired result)
[
{
storeId: 1
storeName: blabla
openingDay: MONDAY
},
{
storeId: 2
storeName: blabla
openingDay: SATURDAY
},
{
storeId: 3
storeName: blabla
openingDay: FRIDAY
}
]
I´ve already found a possible solution, but i´m not satisfied with it:
List<OtherType> transformed = new List<>();
for (Store store : stores) {
for (DayOfWeek currentDay : openingDays) {
transformed.add(new OtherType(.....));
}
}
Is there any possibility to do this with something like 'flatMap(..)' (to be able to use the stream class of java) or another predefined method?
Thank you in advance :)
Deadpool :
By using flatMap
you can achieve this, First stream the stores
list and then in flatMap
stream List<DayOfWeek>
by mapping each DayOfWeek
to 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());