【发布时间】:2021-02-19 19:34:22
【问题描述】:
我希望按特定的 Customer 属性对 Customer 对象的 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 行推断 TreeMapJava(16778094) 的类型参数。
也许,问题在于 Comparator 使用
我将如何解决这个问题以按值排序但保持 customerMap 类型不变?
我知道 TreeMap 仅按键排序。这项工作是否有更好的数据结构,以便我可以存储一堆 Customer 对象并按不同的 Customer 属性对它们进行排序,而操作成本不会太高(最好不是多项式)?
【问题讨论】:
标签: java sorting generics treemap