Search code examples
javatreemap

Java Store data in nested TreeMap


I have a problem. I created the following variable:

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

Then I loop over a list with customers and want each customer to be stored in the customerCache, so I made this code:

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)));
}

But that gives me the error on the TreeMap filling line:

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

To fix this I thought I could convert it to this:

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

Unfortunately, when I run that code I get the next error:

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')

How can I store data in a nested TreeMap


Solution

  • Map.of just doesn't produce anything compatible to TreeMap. You'll have to write your own creator function and use it in customerCache.put.

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