Commit eb75ae76bad6200f081dfa964015ab860add2b43
1 parent
bcce1d95
首页查询占比优化
Showing
1 changed file
with
17 additions
and
7 deletions
urbanops-module-garden/src/main/java/com/zteits/urbanops/module/garden/service/homepage/HomepageSummaryServiceImpl.java
| ... | ... | @@ -29,6 +29,7 @@ import java.time.LocalDateTime; |
| 29 | 29 | import java.time.format.DateTimeFormatter; |
| 30 | 30 | import java.util.*; |
| 31 | 31 | import java.util.stream.Collectors; |
| 32 | +import java.util.stream.IntStream; | |
| 32 | 33 | |
| 33 | 34 | import static com.zteits.urbanops.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId; |
| 34 | 35 | |
| ... | ... | @@ -323,17 +324,26 @@ public class HomepageSummaryServiceImpl implements HomepageSummaryService{ |
| 323 | 324 | if (totalNum <= 0) { |
| 324 | 325 | percents = Collections.singletonList(0); |
| 325 | 326 | } else { |
| 326 | - // 3. 先计算四舍五入占比 | |
| 327 | - List<Integer> tempPercents = workOrderList.stream() | |
| 328 | - .map(vo -> (int) Math.round((vo.getTotal() * 100.0) / totalNum)) | |
| 327 | + List<Integer> tempPercents = workOrderList.stream() | |
| 328 | + .map(vo -> { | |
| 329 | + double percent = (vo.getTotal() * 100.0) / totalNum; | |
| 330 | + int round = (int) Math.round(percent); | |
| 331 | + // 核心:只要 >0 的,至少给 1%,不允许出现 0% | |
| 332 | + return (round == 0 && vo.getTotal() > 0) ? 1 : round; | |
| 333 | + }) | |
| 329 | 334 | .collect(Collectors.toList()); |
| 330 | 335 | |
| 331 | - // 4. 核心:修正总和 = 100%(把差值补到最后一项) | |
| 336 | + // 校准总和 = 100% | |
| 332 | 337 | int sum = tempPercents.stream().mapToInt(Integer::intValue).sum(); |
| 333 | - int diff = 100 - sum; | |
| 338 | + int diff = sum - 100; // 多出来的部分,从最大值减掉 | |
| 339 | + | |
| 334 | 340 | if (diff != 0 && !tempPercents.isEmpty()) { |
| 335 | - int lastIndex = tempPercents.size() - 1; | |
| 336 | - tempPercents.set(lastIndex, tempPercents.get(lastIndex) + diff); | |
| 341 | + // 找出最大值的索引,把差值减掉(最合理,不会出现0) | |
| 342 | + OptionalInt maxIndex = IntStream.range(0, tempPercents.size()) | |
| 343 | + .reduce((i, j) -> tempPercents.get(i) > tempPercents.get(j) ? i : j); | |
| 344 | + if (maxIndex.isPresent()) { | |
| 345 | + tempPercents.set(maxIndex.getAsInt(), tempPercents.get(maxIndex.getAsInt()) - diff); | |
| 346 | + } | |
| 337 | 347 | } |
| 338 | 348 | percents = tempPercents; |
| 339 | 349 | } | ... | ... |