java - Sort ArrayList of custom Objects by property -


i read sorting arraylists using comparator in of examples people used compareto according research method strings.

i wanted sort arraylist of custom objects 1 of properties: date object (getstartday()). compare them item1.getstartdate().before(item2.getstartdate()) wondering whether write like:

public class customcomparator {     public boolean compare(object object1, object object2) {         return object1.getstartdate().before(object2.getstartdate());     } }  public class randomname {     ...     collections.sort(database.arraylist, new customcomparator);     ... } 

since date implements comparable, has compareto method string does.

so custom comparator this:

public class customcomparator implements comparator<myobject> {     @override     public int compare(myobject o1, myobject o2) {         return o1.getstartdate().compareto(o2.getstartdate());     } } 

the compare() method must return int, couldn't directly return boolean planning anyway.

your sorting code wrote:

collections.sort(database.arraylist, new customcomparator()); 

a shorter way write this, if don't need reuse comparator, write inline anonymous class:

collections.sort(database.arraylist, new comparator<myobject>() {     @override     public int compare(myobject o1, myobject o2) {         return o1.getstartdate().compareto(o2.getstartdate());     } }); 

since

you can write last example in shorter form using lambda expression comparator:

collections.sort(database.arraylist,                          (o1, o2) -> o1.getstartdate().compareto(o2.getstartdate())); 

and list has sort(comparator) method, can shorten further:

database.arraylist.sort((o1, o2) -> o1.getstartdate().compareto(o2.getstartdate())); 

this such common idiom there's a built-in method generate comparator class comparable key:

database.arraylist.sort(comparator.comparing(myobject::getstartdate)); 

all of these equivalent forms.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -