gpt4 book ai didi

java - java中如何对具有不同属性的列表进行排序

转载 作者:行者123 更新时间:2023-12-01 06:53:23 28 4
gpt4 key购买 nike

我想要对包含属性名称和类(class)的学生对象列表进行排序,以便根据名称进行排序,如果两个名称相同,那么它应该考虑类(class)进行排序...我可以单独进行,但想要一个列出...请帮忙...

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package studentlist;

import java.util.*;

/**
*
* @author Administrator
*/
public class StudentList {

/**
* @param args the command line arguments
*/
String name, course;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getCourse() {
return course;
}

public void setCourse(String course) {
this.course = course;
}

public StudentList(String name, String course) {
this.name = name;
this.course = course;
}

public static void main(String[] args) {
// TODO code application logic here
List<StudentList> list = new ArrayList<StudentList>();

list.add(new StudentList("Shaggy", "mca"));
list.add(new StudentList("Roger", "mba"));
list.add(new StudentList("Roger", "bba"));
list.add(new StudentList("Tommy", "ca"));
list.add(new StudentList("Tammy", "bca"));

Collections.sort(list, new NameComparator());
Iterator ir = list.iterator();

while (ir.hasNext()) {
StudentList s = (StudentList) ir.next();
System.out.println(s.name + " " + s.course);
}

System.out.println("\n\n\n ");
Collections.sort(list, new CourseComparator());
Iterator ir1 = list.iterator();

while (ir1.hasNext()) {
StudentList s = (StudentList) ir1.next();
System.out.println(s.name + " " + s.course);
}

}

}

class NameComparator implements Comparator<StudentList> {

public int compare(StudentList s1, StudentList s2) {

return s1.name.compareTo(s2.name);

}

}

class CourseComparator implements Comparator<StudentList> {

public int compare(StudentList s1, StudentList s2) {
return s1.course.compareTo(s2.course);
}
}

最佳答案

您只需将两个比较放在一个比较器中即可。

  • 首先测试name是否相等:
    • 如果不相等,则返回name的比较结果。
    • 如果相等,则继续比较类(class):

以下比较器可以工作:

class NameCourseComparator implements Comparator<StudentList> {

public int compare(StudentList s1, StudentList s2) {
if (s1.name.equals(s2.name)) {
return s1.course.compareTo(s2.course);
}
return s1.name.compareTo(s2.name);
}
}

关于java - java中如何对具有不同属性的列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19354529/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com