在TreeSet中,基于不同属性的自定义对象的排序和唯一性

Sma*_*ion 10 java sorting collections unique treeset

以下是我的学生班

class Student implements Comparable {
   String name;
   int rollNo;

   @Override
   public int compareTo(Object obj) {
        return ((Student)obj).name.compareTo(this.name);
   }
} 
Run Code Online (Sandbox Code Playgroud)

最新修改:但仍然没有得到正确的结果

@Override
public int compareTo(Object obj) {
    Student s = (Student) obj;
    if (name.equals(s.name)) { // achieving uniqueness
        return 0;
    } else {
        if (rollNo < s.rollNo) {
            return -1;
        } else if (rollNo > s.rollNo) {
            return 1;
        } else {
            // this makes `name` the second ordering option.
            // names don't equal here
            return name.compareTo(s.name);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我创建了TreeSet <Student>的对象,我将根据唯一名称获取Student对象的排序列表,并按名称排序.

但是我需要在我的TreeSet <Student>中使用student-rollNo订购的唯一学生姓名.

比较器可以吗?任何人都可以帮助我,每个建议都表示赞赏.谢谢.

更新:这是完整的程序:

public class Student implements Comparable {

    int rollNo;
    String name;

    Student(String n,int rno) {
        rollNo=rno;
        name=n;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {

        TreeSet<Student> ts = new TreeSet<Student>();
        ts.add(new Student("bbb",2));
        ts.add(new Student("aaa",4));
        ts.add(new Student("bbb",2));
        ts.add(new Student("ccc",3));
        ts.add(new Student("aaa",1));
        ts.add(new Student("bbb",2));
        ts.add(new Student("bbb",5));

        System.out.println(ts);

    }

    @Override
    public int compareTo(Object obj) {
        Student s = (Student) obj;
        if (name.equals(s.name)) { // achieving uniqueness
            return 0;
        } else {
            if (rollNo < s.rollNo) {
                return -1;
            } else if (rollNo > s.rollNo) {
                return 1;
            } else {
                // this makes `name` the second ordering option.
                // names don't equal here
                return name.compareTo(s.name);
            }
        }
    }

    @Override
    public String toString() {
        return name + rollNo;
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:2:谢谢大家的建议,我还需要更多:)



/*
 * Actual scenario is having different properties,
 * So here I am just relating my actual scenario with Student class
 */
class Student implements Comparable {
    // sorting required on rollNo
    int rollNo;
    // Unique name is required
    String name;

    Student(String n, int rno) {
        rollNo = rno;
        name = n;
    }

    /**
     * 
     * @param args
     */
    public static void main(String[] args) {

        TreeSet<Student> tsName = new TreeSet<Student>();
        // here by default, order & uniqueness by name only
        tsName.add(new Student("ccc", 2));
        tsName.add(new Student("aaa", 4));
        tsName.add(new Student("ddd", 1));
        tsName.add(new Student("bbb", 3));
        tsName.add(new Student("ddd", 5));
        // output: aaa:4, bbb:3, ccc:2, ddd:1
        System.out.println(tsName);

        // creating new comparator for student RollNo
        TreeSet<Student> tsRollNo = new TreeSet<Student>(new Comparator<Student>() {
                    public int compare(Student stud1, Student stud2) {
                        return new Integer(stud1.rollNo).compareTo(stud2.rollNo);
                    }
                });
        tsRollNo.addAll(tsName);
        System.out.println(tsRollNo);
        // now got the desire output: ddd:1, ccc:2, bbb:3, aaa:4
    }

    public boolean equals(Object obj) {
        // internally not used to check equality while adding objects
        // in TreeSet
        System.out.println("equals() for " + this + " & " + ((Student) obj));
        return false;// return false/true doesn't make any sense here
    }

    @Override
    public int compareTo(Object obj) {
        Student s = (Student) obj;
        // internally inside TreeSet, compareTo is used to decide
        // whether two objects are equal or not,
        // i.e. compareTo will return 0 for same object(here student name)
        System.out.println("compareTo() for " + this + " & " + ((Student) obj));
        // achieving uniqueness
        return name.compareTo(s.name);
    }

    @Override
    public String toString() {
        return name + ":" + rollNo;
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

compareTo() for aaa:4 & ccc:2
compareTo() for ddd:1 & ccc:2
compareTo() for bbb:3 & ccc:2
compareTo() for bbb:3 & aaa:4
compareTo() for ddd:5 & ccc:2
compareTo() for ddd:5 & ddd:1
[aaa:4, bbb:3, ccc:2, ddd:1]
[ddd:1, ccc:2, bbb:3, aaa:4]
Run Code Online (Sandbox Code Playgroud)

朋友,无论我使用两个比较器得到什么,是否有可能在添加对象时实现相同的目标?我不能先添加元素然后使用新的比较器来实现所需的顺序.
我正在操纵数以千计的价值,因此也需要考虑性能.

Jig*_*shi 5

TreeSet使用比较器的同时添加元素进行排序和独特检查,

现在的问题是,如果你使用比较器滚动否,你将按照滚动号和唯一滚动nos进行排序.你不能把两者放在一起.

我建议你去.

  1. TreeSet 在这里你专注于重复删除
  2. 然后,一旦您拥有唯一数据ArrayList,就可以按照您想要的任何顺序对其进行排序


Ral*_*lph 1

您可以使用不同的比较器初始化新的 TreeSet。- 所以你所要做的就是编写一个新的Comparator(实现java.util.Comparator接口),使用这个比较器初始化一个新的TreeSet,然后将所有学生添加到该集合中。

TreeSet<Student> sortedByRollNo new TreeSet<Student>(new RollNoComparator());
sortedByRollNo.addAll(allStudents);

TreeSet<Student> sortedByY new TreeSet<Student>(new YComparator());
sortedByY.addAll(allStudents);
Run Code Online (Sandbox Code Playgroud)

每个树集可以有自己的比较器进行排序,如果没有指定比较器,则树集使用集合元素的自然排序。

添加

如果您只需要名称 uniqe Students,那么您有两种方法:

  • 以某种方式实现比较器,如果学生的名字相等,它返回 0(但我相信这是一种黑客行为)。
  • 先按姓名过滤学生,然后按rollNo排序,

有点像这样:

TreeSet<Student> sortedByRollNo new TreeSet<Student>(new RollNoComparator());
sortedByRollNo.addAll(new TreeSet<Student>(allStudends)); //this uses the native comparator to filter by uniqe name
Run Code Online (Sandbox Code Playgroud)