java - 按值对 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 仅按键排序。这项工作是否有更好的数据结构,以便我可以存储一堆客户对象并按不同的客户属性对它们进行排序,而操作成本不会太高(最好不是多项式)?
解决方案
设置第二个 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()] );
'''
推荐阅读
- facebook - 如何使用 Graph API 从 Facebook 广告帐户仅获取 Instagram 广告活动的指标数据
- c - C中的二进制文件通过输入字符串
- qt - QPickTriangleEvent 类的 uvw 属性是什么
- time - 如何在 Rust 中使用 Chrono 库查找时差
- javascript - 使用jquery更改paypal i框架内的按钮样式不起作用
- java - 如何在类路径中链接 DLL 文件
- python - 如何解决错误“ValueError:检查输入时出错:预期 input_1 有 4 个维度,但得到了形状为 (12, 1) 的数组”
- html - html 类名...但不是真的吗?
- rest - 有没有办法在响应完成之前访问 API 响应数据?
- jquery - 如何在 JQuery 中对无序列表中的列表项进行分组?