Reputation: 101
I have a "root" list which contains objects with different lists inside. I have it now divided in 3 operations but i think it could be done using only one so i wouldn't repeat code. Is it possible?
List<Prices[]> pricesList = new ArrayList<Prices>();
List<Instructions[]> instructionsList = new ArrayList<Instructions>();
List<Sizes[]> sizesList = new ArrayList<Sizes>();
/* storesList contains a list of Stores which each of them has
inside a list of prices, instructions and sizes.
I want join all of that individual lists into a single one.*/
storesList.stream()
.map(Devices::getDevicesSubtype)
.filter(Objects::nonNull)
.map(subtype -> (MobileSubtype) subtype)
.map(MobileSubtype::getPrices)
.forEachOrdered(list -> pricesList.add(list));
storesList.stream()
.map(Devices::getDevicesSubtype)
.filter(Objects::nonNull)
.map(subtype -> (MobileSubtype) subtype)
.map(MobileSubtype::getInstructions)
.forEachOrdered(list -> instructionsList.add(list));
storesList.stream()
.map(Devices::getDevicesSubtype)
.filter(Objects::nonNull)
.map(subtype -> (MobileSubtype) subtype)
.map(MobileSubtype::getSizes)
.forEachOrdered(list -> sizesList.add(list));
/*How could i not repeat this part of the code and do the 3 for each ordered?*/
storesList.stream()
.map(Devices::getDevicesSubtype)
.filter(Objects::nonNull)
.map(subtype -> (MobileSubtype) subtype)
Upvotes: 0
Views: 223
Reputation: 54148
Regarding your actual code, I'd suggest one forEach
before mapping to a specific category, then add in each list
storesList.stream()
.map(Devices::getDevicesSubtype)
.filter(Objects::nonNull)
.map(subtype -> (MobileSubtype) subtype)
.forEachOrdered(subtype -> {
pricesList.add(subtype.getPrices());
instructionsList.add(subtype.getInstructions());
sizesList.add(subtype.getSizes());
});
Note : classes should be name at singular if there represent only one element, is Prices
is one price, it should be name Price
to avoid confusion, same for Instructions
and Sizes
Upvotes: 2