首页 > 解决方案 > 按值对 TreeMap 进行排序

问题描述

我正在寻找按特定客户属性对客户对象的 TreeMap 进行排序。TreeMap 是这样定义的:

private TreeMap<Long,Customer> customerMap = new TreeMap<>();

Long 是存储的客户 ID 的类型。

我编写了一个函数来创建一个新的 TreeMap 并将 Comparator 传递给它的构造函数,该构造函数获取映射条目,它们的值,用于比较特定字段。

public Customer[] getCustomersByName() {
    TreeMap<Long,Customer> sortByName = new TreeMap<> (

        new Comparator<Map.Entry<Long,Customer>>() {
            @Override public int compare(Map.Entry<Long,Customer> cus1, Map.Entry<Long,Customer> cus2) {
                return cus1.getValue().getLastName().compareTo(cus2.getValue().getLastName());
            }
        }
    );
    sortByName.putAll(customerMap);
    
    // sortByName to Customer[] and return.

}

这不起作用并抛出:无法在第 2 行推断 TreeMap<>Java(16778094) 的类型参数。

也许,问题在于 Comparator 需要 <Map.Entry<K,V>> 来比较 TreeMap<K,V> ,这就是问题所在。

我将如何解决这个问题以按值排序但保持 customerMap 类型不变?

我知道 TreeMaps 仅按键排序。这项工作是否有更好的数据结构,以便我可以存储一堆客户对象并按不同的客户属性对它们进行排序,而操作成本不会太高(最好不是多项式)?

标签: javasortinggenericstreemap

解决方案


设置第二个 TreeMap,使用客户的姓氏作为键:

TreeMap<String,Customer> sortByName  = new TreeMap<>();
TreeMap<Long,Customer> sortByID = new TreeMap<>();
----------------
sortByName.put(customer.getLastName(), customer);
sortByID.put(new Long(customer.getID()), customer);
----------------
return sortByName.values().toArray( new Customer[sortByName.size()] );
'''

推荐阅读