我想实现下面给出的两种方法。SomeObject有一个Date 类型的字段createdDate
private SomeObject getNearestObjectBeforeTargetObjectsCreatedDate(List<SomeObject> someObjectList, SomeObject targetObject){
}
private SomeObject getNearestObjectAfterTargetObjectsCreatedDate(List<SomeObject> someObjectList, SomeObject targetObject){
}
假设我有 5 个对象 P1、P2、P3、P4、P5 按创建日期的升序排列。目标对象是 P3,那么第一个方法应该返回 P2,第二个应该返回 P4
目前我已经写了这样的东西
private SomeObject getNearestPortFolio(List<SomeObject> someObjectList, SomeObject targetObject){
SomeObject returnObject = targetObject;
for(SomeObject someObject : someObjectList) {
// if the current iteration's date is "before" the target date
if(someObject.getCreatedDate().compareTo(targetObject.getCreatedDate()) < 0) {
if (someObject.getCreatedDate().compareTo(returnObject.getCreatedDate()) > 0){
returnObject = someObject;
}
}
}
return returnObject;
}