如何使用 Java 流对同一个值进行多次映射操作?

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

我有一个“根”列表,其中包含内部具有不同列表的对象。我现在将它分为 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)

关于您的实际代码,我建议在映射到特定类别之前先 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());
        });

注意:类如果只代表一个元素,应该是单数的名字,Prices是一个价格,应该是名字Price,以免混淆,同理InstructionsSizes