Java程序到字母数字排序对象
请让我知道如何才能获得预期的结果
预期产量: B2 D1 D2 D14 E2
实际输出: B2 D1 D14 D2 E2
====================================
List<Name> lst = new ArrayList<>();
lst.add(new Name("D",1));
lst.add(new Name("D",14));
lst.add(new Name("D",2));
lst.add(new Name("E",2));
lst.add(new Name("B",2));
Collections.sort(lst, new Comparator<Name>() {
@Override
public int compare(Name n1, Name n2) {
// TODO Auto-generated method stub
String o1=n1.getNm()+n1.getSeatnum();
String o2=n2.getNm()+n2.getSeatnum();
return o1.compareTo(o2);
}
});
for (Name name : lst) {
System.out.println(name.getNm()+name.getSeatnum());
}
=================================
public class Name {
private String nm;
private int seatnum;
public int getSeatnum() {
return seatnum;
}
public void setSeatnum(int seatnum) {
this.seatnum = seatnum;
}
public Name(String nm) {
super();
this.nm = nm;
}
public Name(String nm, int seatnum) {
super();
this.nm = nm;
this.seatnum = seatnum;
}
public String getNm() {
return nm;
}
public void setNm(String nm) {
this.nm = nm;
}
}
答案 0 :(得分:4)
是的,但是你的compare
函数需要首先检查String
部分是否相等,然后对数字部分使用数字比较(目前,两者都要进行比较{{ 3}})。所以,你可以使用像 -
public int compare(Name n1, Name n2) {
int c = n1.getNm().compareTo(n2.getNm());
if (c != 0) {
return c;
}
return Integer.valueOf(n1.getSeatnum()).compareTo(n2.getSeatnum());
}
答案 1 :(得分:1)
只需将字母与整数进行比较:
public int compare(Name n1, Name n2) {
// TODO Auto-generated method stub
int compare = n1.getNm().compareTo(n2.getNm());
if (compare == 0) {
return Integer.compare(n1.getSeatnum(), n2.getSeatnum());
} else {
return compare;
}
}
答案 2 :(得分:0)
您可以重写比较器,分两步进行:
Collections.sort(lst, new Comparator<Name>() {
@Override
public int compare(Name n1, Name n2) {
// compare the name part
int nameCompare = n1.getName().compareTo(n2.getName());
if(nameCompare != 0)
return nameCompare;
// compare the number part
return n1.getSeatnum() - n2.getSeatnum();
}
});
如果您想了解null
值,请添加:
Collections.sort(lst, new Comparator<Name>() {
@Override
public int compare(Name n1, Name n2) {
// check for null Name
if(n1 == null && n2 == null)
return 0;
else if(n1 == null)
return -1;
else if(n2 == null)
return 1;
// check for null in nx.getName()
if(n1.getName() == null && n2.getName() == null)
return 0;
else if(n1.getName() == null)
return -1;
else if(n2.getName() == null)
return 1;
// compare the name part
int nameCompare = n1.getName().compareTo(n2.getName());
if(nameCompare != 0)
return nameCompare;
// compare the number part
return n1.getSeatnum() - n2.getSeatnum();
}
});
此方法会将null
值放在列表的开头。如果您希望将它们放在列表的末尾,只需交换1
和-1
。
如果您还想要不区分大小写,请将名称比较行修改为:
int nameCompare = n1.getName().toLowerCase().compareTo(n2.getName().toLowerCase());