按值对 TreeMap 进行排序

Sorting TreeMaps by value

我希望按特定客户 属性 对客户对象的 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) 的类型参数。

也许,问题在于比较器使用 > 来比较 TreeMap,这就是问题所在。

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

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

设置第二个 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()] );
'''

这对于流来说相当容易:

Customer[] cust =
    customerMap.values()
               .stream()
               .sorted(Comparator.comparing(Customer::getName))
               .toArray(Customer[]::new);

您只需要根据您的示例对 进行排序,那么当您唯一关心的是排序时,为什么还要对 TreeMap 进行反向排序(按名字)Customer[]?