简体   繁体   中英

Creating a TreeMultimap with Immutable object

I am currently using immutables to construct concrete objects. I am facing an issue while trying to create a TreeMultiMap .

ERROR: It is expecting a comparable in the OrderKey to create the map, How do I set the comparator with immutables to create a 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();
}

One solution is to make sure that your Immutable objects implement the Comparable interface.

If you're using Java 8, this can be achieved using default methods:

@Value.Immutable
interface OrderKey extends Comparable<OrderKey> {
    long orderNum();

    default int compareTo(OrderKey o) {
        return orderNum() - o.orderNum();
    }
}

If you're pre-java 8, consider using abstract classes instead of interfaces to achieve the same effect.


Another approach (again java 8) is to supply comparators to the the creation method, eg:

Comparator<OrderKey> orderKeyCmp = Comparator.comparingLong(OrderKey::orderNum);
Comparator<Order> orderCmp = Comparator.comparing(Order::orderDate);

SortedSetMultimap<ImmutableOrderKey, ImmutableOrder> orderMap 
    = TreeMultimap.create(orderKeyCmp, orderCmp);

The above will sort OrderKey instances according to the orderNum field, and Order instances according to the orderDate field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM