2

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 :)

  • Your attribute in Java i.e `List openiningDays;` contradicts the JSON `openingDay: MONDAY` which is not a collection and what is the model for `OtherType`? – Naman Jul 31 '19 at 16:49
  • 1
    this is just a modified example of a real business use-case. so in this case that doesn´t matter. But thank you for your hint. The code snippet containing 'openingDay: Monday' shows what the result of the mapping should look like'. Not what an instance of the inital model could look like. The 'OtherType' model, regarding to this example, contains the variables 'storeID' 'storeName' and a single 'weekDay' –  Jul 31 '19 at 18:22

1 Answers1

2

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());
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98