简体   繁体   English

番石榴订购通用

[英]Guava generic for Ordering

I have quite big issue with create generic method for Ordering. 创建订购通用方法有很大的问题。 At this moment I have this function : 目前,我具有以下功能:

public <T> T orderAscending(Function<?, ? extends Comparable> function, Iterable<? extends LinkedList<?>> sortingList) {
    return Ordering.natural().onResultOf(function).sortedCopy(sortingList);
}

First parameter of this function is created in this way : 该函数的第一个参数是通过以下方式创建的:

public static Function<ParkingWebApiDTO, Date> getSortActiveParkingsByStartDate() {
        Function<ParkingWebApiDTO, Date> getStartDateFunction = new Function<ParkingWebApiDTO, Date>() {
            @Override
            public Date apply(ParkingWebApiDTO parkingWebApiDTO) {
                return parkingWebApiDTO.getStartDate();
            }
        };
        return getStartDateFunction;
    }

and the second one is LinkedList with some custom object in it ( List<MyObject> test = new LinkedList<MyObject>() ). 第二个是其中包含一些自定义对象的LinkedList( List<MyObject> test = new LinkedList<MyObject>() )。

Please someone help me to fix this generic method orderAscending . 请有人帮助我修复此通用方法orderAscending Much appreciated for help. 非常感谢您的帮助。

I guess you meant to create List (sorted by start date) from Iterable of your DTOs (I assume you don't want iterable of lists of DTOs). 我猜您打算从DTO的Iterable创建List (按开始日期排序)(我假设您不希望DTO的列表可迭代)。

So let's say your DTO looks like this: 因此,假设您的DTO如下所示:

interface ParkingWebApiDTO { // could be simple class, etc.
  Date getStartDate();
  // ...and more methods here
}

you have input list: 您有输入列表:

LinkedList<? extends ParkingWebApiDTO> iterable = Lists.newLinkedList();

and function which retrieves start date from DTO: 和从DTO检索开始日期的函数:

Function<ParkingWebApiDTO, Date> function = new Function<ParkingWebApiDTO, Date>() {
  @Override
  public Date apply(ParkingWebApiDTO dto) {
    return dto.getStartDate();
  }
};

you expect output like this: 您期望这样的输出:

List<? extends ParkingWebApiDTO> result = orderAscending(function, iterable);

which can be achieved with following orderAscending imlementation : 这可以通过以下orderAscending实现

public static <X, T extends Comparable<T>> List<? extends X> orderAscending(
    Function<X, T> function, Iterable<? extends X> sortingList) {
  return Ordering.natural().onResultOf(function).sortedCopy(sortingList);
}

You need to declare both from and to types as generic types if you want to have "universal" method. 如果要具有“通用”方法,则需要将from和to类型都声明为泛型类型。

Another thing is if you really need to have such generic name, because using Ordering.natural().onResultOf(function).sortedCopy(list) is perfectly fine and having orderAscending is IMO overkill (you'll end with plenty of methods like this one). 另一件事是,如果您确实需要使用这样的通用名称,因为使用Ordering.natural().onResultOf(function).sortedCopy(list)非常好,而orderAscending是IMO的大材小用(您将以许多这样的方法结束一)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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