Java 将数据存储在嵌套的 TreeMap 中

Java Store data in nested TreeMap

我有问题。我创建了以下变量:

TreeMap<String, TreeMap<Long, Customer>> customerCache = new TreeMap<>();

然后我遍历一个包含客户的列表,并希望每个客户都存储在 customerCache 中,所以我编写了以下代码:

customerCache.clear();
for (int i = customers.size() - CUSTOMER_CACHE_SIZE; i < customers.size(); i++) {
    String customerKey = "group1";
    customerCache.put(customerKey , Map.of(customers.get(i).getCreatedTime(), customers.get(i)));
}

但这给了我 TreeMap 填充行上的错误:

Type mismatch: cannot convert from Map<Long,Customer> to TreeMap<Long,Customer>

为了解决这个问题,我想我可以把它转换成这个:

customerCache.put(customerKey, (TreeMap<Long, Customer>) Map.of(customers.get(i).getCreatedTime(), customers.get(i)));

不幸的是,当我 运行 该代码时,我得到了下一个错误:

Exception in thread "main" java.lang.ClassCastException: class java.util.ImmutableCollections$Map1 cannot be cast to class java.util.TreeMap (java.util.ImmutableCollections$Map1 and java.util.TreeMap are in module java.base of loader 'bootstrap')

如何在嵌套的 TreeMap 中存储数据

Map.of 只是不产生任何与 TreeMap 兼容的东西。您必须编写自己的创建者函数并在 customerCache.put.

中使用它
private TreeMap<Long, Customer> create(Long id, Customer customer){
    TreeMap<Long, Customer>  result = new TreeMap<>();
    result.put(id, customer);
    return result;
}