我希望根据特定的Customer属性对Customer对象的TreeMap进行排序。TreeMap的定义如下:
private TreeMap<Long,Customer> customerMap = new TreeMap<>();Long是存储的客户的ID类型。
我编写了一个函数来创建一个新的TreeMap,并将一个比较器传递给它的构造函数,该构造函数获取比较特定字段的映射条目及其值。
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类型不变?
我知道TreeMaps只按键排序。这个工作是否有一个更好的数据结构,这样我就可以存储一堆客户对象,并根据不同的客户属性对它们进行排序,而不需要太昂贵的操作(最好不是多项式)?
发布于 2021-02-19 20:21:25
设置第二个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()] );
'''发布于 2021-02-19 20:24:08
对于流来说,这相当容易:
Customer[] cust =
customerMap.values()
.stream()
.sorted(Comparator.comparing(Customer::getName))
.toArray(Customer[]::new);您只需要根据示例对值进行排序,那么为什么要对TreeMap进行反向排序,因为您只关心一个排序(按名称)的Customer[]。
https://stackoverflow.com/questions/66283947
复制相似问题