sorting - How to sort Arraylist consisting of pojo class in java -
i have pojo class student this
class student { private int score; private string firstname; //getters , setters ................. }
i creating arraylist this
public static void main(string[] args) { list<student> al_students= new arraylist<student>(); student s1= new student(); s1.setscore(90); s1.setfirstname("abc"); al_students.add(s1); student s2= new student(); s2.setscore(95); s2.setfirstname("def"); al_students.add(s2); student s3= new student(); s3.setscore(85); s3.setfirstname("xyz"); al_students.add(s3); }
now want sort based on scores in descending order i.e
output
1)def 95 2)abc 90 3)xyz 85
you can use custom comparator
.
here's full example (imports excluded):
public class main { // main method setting , printing students public static void main(string[] args) { list<student> students = new arraylist<student>(); student s1 = new student(); s1.setscore(90); s1.setfirstname("abc"); students.add(s1); student s2 = new student(); s2.setscore(95); s2.setfirstname("def"); students.add(s2); student s3 = new student(); s3.setscore(85); s3.setfirstname("xyz"); students.add(s1); system.out.printf("unordered: %s%n", students); // sorting using anonymous comparator collections.sort(students, new comparator<student>() { public int compare(student s1, student s2) { // notice cast (integer) invoke compareto return ((integer)s1.getscore()).compareto(s2.getscore()); } }); system.out.printf("ordered: %s%n", students); } // student class static class student { private int score; private string firstname; // boring stuff public int getscore() { return score; } public void setscore(int score) { this.score = score; } public string getfirstname() { return firstname; } public void setfirstname(string name) { this.firstname = name; } // printing @override public string tostring() { return string.format("student \"%s\" score: %d%n", firstname, score); } } }
output
unordered: [student "abc" score: 90 , student "def" score: 95 , student "abc" score: 90 ] ordered: [student "abc" score: 90 , student "abc" score: 90 , student "def" score: 95 ]
note
as others mention, can implement comparable<student>
in student
class, if (or default) sorting score.#
second edit
in order sort in decreasing order, can replace return
statement in comparator
following:
return ((integer)s2.getscore()).compareto(s1.getscore());
thanks programminglover spotting / apologies mistakenly rejecting edit!
Comments
Post a Comment