java - Find the closest object (before and after) to the target object -


i want implement 2 methods given below. someobject has field createddate of type date

private someobject getnearestobjectbeforetargetobjectscreateddate(list<someobject> someobjectlist, someobject targetobject){  }   private someobject getnearestobjectaftertargetobjectscreateddate(list<someobject> someobjectlist, someobject targetobject){  } 

suppose have 5 objects p1, p2, p3, p4, p5 in ascending order of created dates. , target object p3, 1st method should return p2 , second should return p4

currently have wirtten this

private someobject getnearestportfolio(list<someobject> someobjectlist, someobject targetobject){     someobject returnobject = targetobject;        for(someobject someobject : someobjectlist) {         // if current iteration's date "before" target date           if(someobject.getcreateddate().compareto(targetobject.getcreateddate()) < 0) {                if (someobject.getcreateddate().compareto(returnobject.getcreateddate()) > 0){                   returnobject = someobject;           }        }      }       return returnobject;     } 

you can this. make sure make necessary changes per needs, core logic stay same.

// note if target first element, return null. private static string getnearestbefore(list<string> test, string target) {     string returnobj = null;     string previous = null;     (string someobj : test) {         if (someobj.equals(target)) { //insert condition here             returnobj = previous;         }         previous = someobj;     }     return returnobj; }  // note if target last element, return null. private static string getnearestafter(list<string> test, string target) {     string returnobj = null;     boolean nextsatisfied = false;     (string someobj : test) {         if (nextsatisfied) {             returnobj = someobj;             break;         }         if (someobj.equals(target)) { //insert condition here             nextsatisfied = true;         }     }     return returnobj; } 

Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -