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 15:03:15 浏览: 216
可以使用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方法,避免了多层嵌套循环的问题,提高了代码的可读性和性能。
相关问题
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()); break; } } } 使用 stream优化
可以使用 Java 8 引入的 Stream API 来优化上述代码。具体实现方式如下:
```
blockSubscriptions.forEach(blockSubscription ->
subscriptionCountList.stream()
.filter(blockSubscriptionData -> blockSubscription.getId() == blockSubscriptionData.getActivityId())
.findFirst()
.ifPresent(blockSubscriptionData -> blockSubscription.setSubscriptionCount(blockSubscriptionData.getSubscriptionCount())));
blockSubscriptions.forEach(blockSubscription ->
subscriptionPeopleCountList.stream()
.filter(blockSubscriptionData -> blockSubscription.getId() == blockSubscriptionData.getActivityId())
.findFirst()
.ifPresent(blockSubscriptionData -> blockSubscription.setSubscriptionPeopleCount(blockSubscriptionData.getSubscriptionPeopleCount())));
```
上面的代码中,我们使用 forEach 方法遍历 blockSubscriptions 列表,然后使用 Stream API 进行过滤、查找以及设置属性值。这样做的好处是代码更加简洁,可读性更高,同时也可以提高代码的执行效率。
阅读全文