Reputation: 738
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>()
).
Please someone help me to fix this generic method orderAscending
. Much appreciated for help.
Upvotes: 0
Views: 206
Reputation: 28015
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).
So let's say your DTO looks like this:
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:
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:
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.
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).
Upvotes: 1