优化下面代码 for (int i = 0; i < 10; i++) { long sum = detailList.stream().mapToLong(detail -> detail.getCells().get(i).getPeople()).sum(); }
时间: 2024-03-09 08:45:31 浏览: 14
可以将 detailList.stream() 提取到循环外部,同时使用并行流来提高计算效率。代码如下:
```
IntStream.range(0, 10)
.parallel()
.forEach(i -> {
long sum = detailList.parallelStream()
.mapToLong(detail -> detail.getCells().get(i).getPeople())
.sum();
// do something with sum
});
```
这样可以避免每次都创建一个流对象,同时并行流可以利用多线程来提高计算效率。
相关问题
使用中文解释以下代码: // 获取奖池数据 List<PasturePrize> pasturePrizes = baseMapper.selectList(); // 中奖总率 long sum = pasturePrizes.stream().mapToLong(PasturePrize::getPrizeRate).sum(); // 随机生成一个中奖数 Random random = new Random(); int luckNum = random.nextInt((int) sum); Integer tmp = 0; Integer tmp2 = 0; for (int i = 0; i < pasturePrizes.size(); i++) { if (tmp2 == 0) { tmp2 = pasturePrizes.get(0).getPrizeRate(); } if (luckNum >= tmp && luckNum <= tmp2){ PasturePrizeRecord pasturePrizeRecord = new PasturePrizeRecord(); pasturePrizeRecord.setPrizeName(pasturePrizes.get(i).getPrizeName()); pasturePrizeRecord.setPhone(user.getPhone()); pasturePrizeRecord.setPrizePrice(pasturePrizes.get(i).getPrizePrice()); if(pasturePrizes.get(i).getPrizeType().equals("积分")){ pasturePrizeRecord.setPrizeType("积分"); }else { pasturePrizeRecord.setPrizeType("现金"); } pasturePrizeRecord.setUserId(user.getId()); pasturePrizeRecord.setUsername(user.getUsername()); pasturePrizeRecordMapper.insert(pasturePrizeRecord); if (pasturePrizes.get(i).getPrizeType().equals("现金")){ user.setBalance(pasturePrizes.get(i).getPrizePrice().add(user.getBalance())); }else { user.setFeed(pasturePrizes.get(i).getPrizePrice().add(user.getFeed())); } user.setDrawLotteryRaffleTotal(user.getDrawLotteryRaffleTotal() - 1); pastureUserMapper.updateById(user); return pasturePrizes.get(i); } else { if (tmp == 0L){ tmp = tmp + pasturePrizes.get(i).getPrizeRate(); } else { if (i < pasturePrizes.size() - 1){ tmp = tmp2; } } if (i< pasturePrizes.size() - 1){ tmp2 = tmp2 + pasturePrizes.get(i + 1).getPrizeRate(); } } }
这段代码是获取奖池数据,计算中奖总率,随机生成一个中奖数,然后根据中奖数在奖池中匹配对应的奖品。具体实现是通过遍历奖池中的每个奖品,将每个奖品的中奖率相加得到中奖总率,然后随机生成一个中奖数,再通过遍历奖池中的每个奖品,累加每个奖品的中奖率,直到累加值大于等于随机生成的中奖数,即可确定中奖的奖品。
int votes = mapList.stream().mapToInt(map -> (int) map.get("votes")).sum();报错java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer
这个错误可能是由于"votes"字段的类型不一致导致的。在代码中,您将"votes"字段转换为整数类型`(int)`,但实际上它可能是长整型`(Long)`。
为了解决这个问题,您可以尝试将"votes"字段转换为长整型`(Long)`,然后再将其转换为整数类型。以下是修改后的代码:
```java
int votes = mapList.stream()
.map(map -> (Long) map.get("votes"))
.mapToInt(Long::intValue)
.sum();
```
在这个修改后的代码中,我们首先将"votes"字段转换为长整型`(Long)`,然后使用`mapToInt`方法将其转换为整数类型。这样就可以避免出现将长整型`(Long)`直接转换为整数类型`(int)`时的错误。
希望这次能解决您的问题!如果还有其他疑问,请随时提问。