You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将嵌套循环代码转为Java Stream并正确创建ProfitOption对象?

嵌套循环转Stream实现方案

直接给出符合函数式编程要求、无副作用的Stream实现代码,完全对应原嵌套循环的逻辑:

Island buyIsland = islandCargoPriceDataTable.get(buyIslandName);
Collection<Island> islandList = islandCargoPriceDataTable.values();
Ship ship = shipPropertiesInfo.get(shipName);

List<ProfitOption> profitOptions = buyIsland.getIslandCargoPrices().keySet().stream()
    .flatMap(cargoName -> {
        // 获取当前货物的买入价,在flatMap内部捕获该值供后续使用
        int cargoBuyPrice = buyIsland.getIslandCargoPrices().get(cargoName).getPrice();
        // 遍历所有售卖岛屿,过滤出盈利场景并生成ProfitOption
        return islandList.stream()
            .filter(sellIsland -> {
                int cargoSellPrice = sellIsland.getIslandCargoPrices().get(cargoName).getPrice();
                return cargoSellPrice > cargoBuyPrice;
            })
            .map(sellIsland -> new ProfitOption(buyIsland, cargoName, sellIsland, ship, levelOfDetail));
    })
    .collect(Collectors.toList());

逻辑对应说明

  1. 用buyIsland.getIslandCargoPrices().keySet().stream()替代外层的货物名称循环
  2. 通过flatMap实现嵌套循环的扁平化处理,同时在lambda内部捕获当前货物的买入价,确保内层操作能访问到该值
  3. 内层用filter替代原代码中“售价大于买入价”的判断条件,只保留盈利的场景
  4. 符合条件的组合直接通过map转换为ProfitOption对象,最后用collect生成结果列表,全程无外部集合修改等副作用

内容的提问来源于stack exchange,提问作者Reborn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 13:15:32