In this example we will show two ways to sort a TreeSet with user defined objects, just as follows.
Source Code
– Student class
package com.beginner.examples;
public class Student implements Comparable {
private String stuName;
private int age;
private String gender;
public Student() {
}
public Student(String stuName, int age , String gender) {
this.stuName = stuName;
this.age = age;
this.gender = gender;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return this.stuName + "," + this.age + "," + gender;
}
@Override
public int compareTo(Student stu) {
//Comparative age first
int num1 = this.age - stu.getAge();
// Same age, compare name
int num2= num1==0?this.stuName.compareTo(stu.getStuName()):num1;
return num2;
}
}
– TestTreeSet
package com.beginner.examples;
import java.util.Iterator;
import java.util.TreeSet;
public class TestTreeSet {
public static void main(String[] args) {
TreeSet set = new TreeSet();
set.add(new Student("Tom", 22, "male"));
set.add(new Student("Jerry", 21, "male"));
set.add(new Student("Ruth", 23, "female"));
set.add(new Student("John", 19, "male"));
// Traverse the collection to see the order of the elements
for (Iterator i = set.iterator(); i.hasNext();) {
Student student = i.next();
System.out.println(student);
}
}
}
Output:
John,19,male
Jerry,21,male
Tom,22,male
Ruth,23,female
– TestTreeSet2
package com.beginner.examples;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
public class TestTreeSet2 {
public static void main(String[] args) {
//In this way, you need to create a comparator object (using the anonymous inner class approach here)
TreeSet set = new TreeSet(new Comparator() {
@Override
public int compare(Student stu1, Student stu2) {
int num1 = stu1.getAge() - stu2.getAge();
int num2 = num1 == 0 ? stu1.getStuName().compareTo(stu2.getStuName()) : num1;
return num2;
}
});
set.add(new Student("Tom",23,"male"));
set.add(new Student("Jerry",22,"male"));
set.add(new Student("Ruth",22,"female"));
set.add(new Student("John",21,"female"));
// Traverse the collection to see the order of the elements
for (Iterator i = set.iterator(); i.hasNext();) {
Student student = i.next();
System.out.println(student);
}
}
}
Output:
John,21,female
Jerry,22,male
Ruth,22,female
Tom,23,male
References
Imported packages in Java documentation: