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

如何高效判断用户的所有城市列表是否一致(无序、大小写不敏感)

问题描述

每个用户拥有0个或N个仅含唯一值的城市列表,需要高效判断所有列表是否完全一致(顺序无关、所有值大小写不敏感)。相关代码定义如下:

用户模型

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
static class User{
    private Map<Integer, List<String>> cities;
}

待实现的比较方法

private static boolean isListsIdentical(User user) {
    user.getCities().values().forEach(cities -> {
        // 若所有列表都一致则返回true
    });
    return false;
}

测试主方法

public static void main(String[] args) {
    User user = new User();
    Map<Integer, List<String>> cities = new HashMap<>();
    cities.put(1, Arrays.asList("New York City", "London", "Paris", "Tokyo", "LA"));
    cities.put(2, Arrays.asList("Beijing", "Hong Kong", "Chicago"));
    cities.put(3, Arrays.asList("New York City", "London", "Paris", "Tokyo", "LA"));
    cities.put(4, null);
    user.setCities(cities); // 用户可能有0个或N个列表

    System.out.println(isListsIdentical(user)); // 此案例应返回false
}
解决方案

核心思路是统一转换列表为大小写不敏感的无序集合,再以第一个有效集合为基准逐一比对:

  1. 处理空值、空列表等边界情况,统一转换为标准空集合
  2. 将每个城市列表转成存储小写城市名的HashSet(自动忽略顺序,大小写不敏感)
  3. 以第一个有效集合为基准,只要有一个集合和基准不一致就立即返回false

实现代码如下:

private static boolean isListsIdentical(User user) {
    // 无城市列表时直接返回true
    if (user == null || user.getCities() == null || user.getCities().isEmpty()) {
        return true;
    }

    Set<String> baseSet = null;
    for (List<String> cityList : user.getCities().values()) {
        Set<String> currentSet;
        // 处理null或空列表
        if (cityList == null || cityList.isEmpty()) {
            currentSet = Collections.emptySet();
        } else {
            currentSet = new HashSet<>();
            for (String city : cityList) {
                if (city != null) {
                    // 转小写+去空格,保证大小写、空格不敏感
                    currentSet.add(city.trim().toLowerCase());
                }
            }
        }

        // 初始化基准集合
        if (baseSet == null) {
            baseSet = currentSet;
            continue;
        }

        // 比对不一致直接返回false
        if (!baseSet.equals(currentSet)) {
            return false;
        }
    }
    return true;
}

代码说明

  • 覆盖了用户为null、城市Map为空、列表为null、列表为空、列表含null元素等所有异常场景
  • 转小写+去空格的处理,确保"New York"和" new york "这类情况被视为相同
  • 一旦发现不一致立即返回,避免不必要的遍历,保证效率
  • 测试案例中,因为存在内容不同的列表2,以及和基准集合不一致的null列表,所以返回false,符合预期

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 00:40:28