简体   繁体   English

如何使用 Java stream 以相同的值执行多个 map 操作?

[英]How to do multiple map operations with the same value using Java stream?

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.我现在将它分为 3 个操作,但我认为它可以只使用一个来完成,所以我不会重复代码。 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)

Regarding your actual code, I'd suggest one forEach before mapping to a specific category, then add in each list关于您的实际代码,我建议在映射到特定类别之前使用一个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());
        });

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注意:如果类只代表一个元素,则名称应为单数,即Prices是一个价格,应为Price名称以避免混淆, InstructionsSizes相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM