for (BlockSubscription blockSubscription : blockSubscriptions) { for (BlockSubscriptionData blockSubscriptionData : subscriptionCountList) { if (blockSubscription.getId() == blockSubscriptionData.getActivityId()){ blockSubscription.setSubscriptionCount(blockSubscriptionData.getSubscriptionCount()); } } for (BlockSubscriptionData blockSubscriptionData : subscriptionPeopleCountList) { if (blockSubscription.getId() == blockSubscriptionData.getActivityId()){ blockSubscription.setSubscriptionPeopleCount(blockSubscriptionData.getSubscriptionPeopleCount()); } } }使用Stream优化
时间: 2024-01-15 12:03:15 浏览: 220
可以使用Stream API对这段代码进行优化,如下所示:
```
blockSubscriptions.forEach(blockSubscription -> {
subscriptionCountList.stream()
.filter(data -> blockSubscription.getId() == data.getActivityId())
.findFirst()
.ifPresent(data -> blockSubscription.setSubscriptionCount(data.getSubscriptionCount()));
subscriptionPeopleCountList.stream()
.filter(data -> blockSubscription.getId() == data.getActivityId())
.findFirst()
.ifPresent(data -> blockSubscription.setSubscriptionPeopleCount(data.getSubscriptionPeopleCount()));
});
```
这段代码使用了Stream的filter和findFirst方法,避免了多层嵌套循环的问题,提高了代码的可读性和性能。
阅读全文