gpt4 book ai didi

java - 使用 Immutable 对象创建 TreeMultimap

转载 作者:行者123 更新时间:2023-12-02 02:33:57 25 4
gpt4 key购买 nike

我目前正在使用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 实例进行排序,并根据 orderDateOrder 实例进行排序字段。

关于java - 使用 Immutable 对象创建 TreeMultimap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46670622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com