我有一個“根”串列,其中包含內部具有不同串列的物件。我現在將它分為 3 個操作,但我認為它可以只使用一個來完成,所以我不會重復代碼。是否可以?
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)
uj5u.com熱心網友回復:
關于您的實際代碼,我會forEach在映射到特定類別之前建議一個,然后添加到每個串列中
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());
});
注意:如果類只代表一個元素,則名稱應為單數,isPrices是一種價格,應為名稱Price以避免混淆,Instructions與Sizes
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/408238.html
標籤:
