gpt4 book ai didi

java - 如何使用 arraylist 根据用户定义的排序对类对象进行排序?

转载 作者:行者123 更新时间:2023-11-30 07:28:04 25 4
gpt4 key购买 nike

我正在使用arreyList中的比较器对类对象进行排序,我是根据名称的字母顺序排序对象
比较器的来源(如果低于)

public static Comparator<SortingObjects StuNameComparator = new Comparator<SortingObjects() {

public int compare(SortingObjects s1, SortingObjects s2) {
String StudentName1 = s1.getName().toUpperCase();
String StudentName2 = s2.getName().toUpperCase();
int c;

c = StudentName1.compareTo(StudentName2);



if(c==0){
int rollno1 = s1.getPrice();
int rollno2 = s2.getPrice();
c = rollno1-rollno2;
}


return c;

}};

其给出的结果如下:

 Student Name Sorting:   


[ name=AP, price =0]
[ name=AP, price =0]
[ name=AP, price =0]
[ name=AP, price =0]
[ name=CH, price =0]
[ name=CH, price =0]
[ name=CH, price =0]
[ name=CH, price =0]
[ name=KE, price =0]
[ name=KE, price =0]
[ name=TN, price =0]

但我想要像这样的输出:

[ name=CH, price =3]    
[ name=CH, price =10]
[ name=AP, price =2]
[ name=AP, price =2]
[ name=AP, price =7]
[ name=AP, price =10]
[ name=TN, price =15]
[ name=KE, price =2]
[ name=KE, price =5]

这意味着:“CH”首先出现,然后是“AP”,然后是“TN”,最后
“KE”有什么方法可以实现比较方法,以便我可以得到结果由自己定义的排序

最佳答案

您可以将排序存储到数组中并将其用作比较器:

public static Comparator<SortingObjects StuNameComparator = new Comparator<SortingObjects() {
List ordering = Arrays.asList("CH","AP","TN","KE");
public int compare(SortingObjects s1, SortingObjects s2) {

return ordering.indexOf(s1.name) - ordering.indexOf(s2.name);

}};

这只是一个片段,它应该是这样的。

关于java - 如何使用 arraylist 根据用户定义的排序对类对象进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36543187/

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