java - How can I sort an ArrayList of objects? -
i have , arraylist
2 strings , integer
, need sort string name
, string lastname
, tried method collections.sort
this
collections.sort(myarraylist, (contact v1, contact v2) -> v1.getname().compareto(v2.getname()));
but sorts arraylist
names, , doesn't include last name, how can add sort last names?
well need change comparison function include other fields this
collections.sort(contacts, (contact c1, contact c2) -> { int firstnamecomparisonresult = c1.getfirstname().compareto(c2.getfirstname()); if (firstnamecomparisonresult != 0) { return firstnamecomparisonresult; } else { return c1.getlastname().compareto(c2.getlastname()); } });
warning: assumes there no nulls.
full code used if want take look:
class contact{ final string firstname; final string lastname; final int age; public string getfirstname() { return firstname; } public string getlastname() { return lastname; } public int getage() { return age; } public contact(string firstname, string lastname, int age) { this.firstname = firstname; this.lastname = lastname; this.age = age; } @override public string tostring() { return "contact{" + "firstname='" + firstname + '\'' + ", lastname='" + lastname + '\'' + ", age=" + age + '}'; } } @test public void sorttest(){ list<contact> contacts = new arraylist<>(); contacts.add(new contact("a","b",37)); contacts.add(new contact("a","c",34)); contacts.add(new contact("b","a",35)); collections.sort(contacts, (contact c1, contact c2) -> { int firstnamecomparisonresult = c1.getfirstname().compareto(c2.getfirstname()); if (firstnamecomparisonresult != 0) { return firstnamecomparisonresult; } else { return c1.getlastname().compareto(c2.getlastname()); } }); system.out.println(contacts); //[contact{firstname='a', lastname='b', age=37}, contact{firstname='a', lastname='c', age=34}, contact{firstname='b', lastname='a', age=35}] }
Comments
Post a Comment