我目前正在使用immutables构造具体的物体。
我在尝试创建 TreeMultiMap
时遇到问题。
错误:它需要 OrderKey
中的可比项来创建 map ,
如何使用不可变值设置比较器来创建 TreeMultiMap
?
//Does not compile here
SortedSetMultimap<ImmutableOrderKey, ImmutableOrder > orderMap= TreeMultimap.create();
@Value.Immutable
interface OrderKey {
long orderNum();
}
@Value.Immutable
interface Order {
long orderNum();
DateTime orderDate();
String deliveryAddress();
}
最佳答案
一种解决方案是确保您的 Immutable 对象实现 Comparable
接口(interface)。
如果您使用的是 Java 8,则可以使用默认方法来实现:
@Value.Immutable
interface OrderKey extends Comparable<OrderKey> {
long orderNum();
default int compareTo(OrderKey o) {
return orderNum() - o.orderNum();
}
}
如果您是 java 8 之前的版本,请考虑使用抽象类而不是接口(interface)来达到相同的效果。
<小时/>另一种方法(同样是 java 8)是为创建方法提供比较器,例如:
Comparator<OrderKey> orderKeyCmp = Comparator.comparingLong(OrderKey::orderNum);
Comparator<Order> orderCmp = Comparator.comparing(Order::orderDate);
SortedSetMultimap<ImmutableOrderKey, ImmutableOrder> orderMap
= TreeMultimap.create(orderKeyCmp, orderCmp);
上面将根据 orderNum
字段对 OrderKey
实例进行排序,并根据 orderDate
对 Order
实例进行排序字段。
关于java - 使用 Immutable 对象创建 TreeMultimap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46670622/