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

优化代码设计提升性能:如何减少冗余循环实现日期分组、排序及DTO编号

优化方案

你当前的代码实际为3次循环,可通过合并逻辑、简化API调用进一步优化,最终可将循环次数降低为2次,同时减少冗余对象创建,代码简洁度也会明显提升。

核心优化点

  • 分组逻辑优化:将循环内重复创建SimpleDateFormat、冗余ArrayList初始化、containsKey判断的逻辑替换为computeIfAbsentAPI实现,单次遍历即可完成分组
  • 合并遍历逻辑:将原有的「列表排序」「ID分配」两次Map遍历合并为一次,减少遍历开销
  • 修复原代码笔误:原排序循环中泛型误写为BookingDTO,需统一为BookDTO

优化后代码(兼容Java 7及以上版本)

int serialNumber = 1;
if (hList != null && !hList.isEmpty()) {
    HashMap<String, ArrayList<BookDTO>> mapObj = new HashMap<>();
    // 移到循环外创建,避免重复实例化
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    // 单次遍历完成分组
    for (Object obj : hList) {
        BookDTO bookDTO = (BookDTO) obj;
        Calendar depDate = bookDTO.getDepartureDate();
        if (depDate != null) {
            String formattedDate = format.format(depDate.getTime());
            // computeIfAbsent简化判断:存在则返回已有列表,不存在则创建新列表放入Map
            mapObj.computeIfAbsent(formattedDate, k -> new ArrayList<>()).add(bookDTO);
        }
    }
    // 单次遍历同时完成排序、ID分配
    BookDTOComparator comparator = new BookDTOComparator(DATES);
    for (ArrayList<BookDTO> bookList : mapObj.values()) {
        Collections.sort(bookList, comparator);
        serialNumber = setItinerarySerialNumber(bookList, serialNumber);
    }
}

Java 8+ 进一步简化版本(用Stream API实现分组)

int serialNumber = 1;
if (hList != null && !hList.isEmpty()) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
    // Stream一行完成分组过滤
    Map<String, List<BookDTO>> mapObj = hList.stream()
            .map(obj -> (BookDTO) obj)
            .filter(bookDTO -> bookDTO.getDepartureDate() != null)
            .collect(Collectors.groupingBy(bookDTO -> 
                formatter.format(Instant.ofEpochMilli(bookDTO.getDepartureDate().getTimeInMillis())
                        .atZone(ZoneId.systemDefault())
                        .toLocalDate())
            ));
    // 统一处理排序和ID分配
    BookDTOComparator comparator = new BookDTOComparator(DATES);
    for (List<BookDTO> bookList : mapObj.values()) {
        bookList.sort(comparator);
        serialNumber = setItinerarySerialNumber(new ArrayList<>(bookList), serialNumber);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 23:45:03