collections.sort 中文排序 降序

public class People{
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public People(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "people [ name=" + name + ", age=" + age + "]";

}



public class peopleTest {
public static void main(String[] args) {
List<People> listp=new ArrayList<>();
People p1=new People("张三", 199);
People p2=new People("李四", 200);
People p3=new People("王五", 198);
People p4=new People("赵六", 200);
listp.add(p1);
listp.add(p2);
listp.add(p3);
listp.add(p4);
Collections.sort(listp,new nComparator());
myprint(listp);
}

public static void myprint(List<People> list){
Iterator it=list.iterator();
while(it.hasNext()){
System.out.println("\t"+it.next());
}
}

static class nComparator implements Comparator{
public int compare(Object  o1, Object o2){
People p1=(People)o1;
People p2=(People)o2;
//先年龄比较降序  年龄相同然后名字比较升序
int result=p1.getAge()>p2.getAge()?-1:(p1.getAge()==p2.getAge()?0:1);//降序
//int result1=p1.getAge()>p2.getAge()?1:(p1.getAge()==p2.getAge()?0:-1);//升序
if(result==0){
result=toUTF_8(p1.getName()).compareTo(toUTF_8(p2.getName()));
}
return result;
}
}
//中文进行比较 需要把字符串转换编码为iso-8859-1
private static String toUTF_8(String str) {  
    try {  
        return new String(str.getBytes(), "ISO-8859-1");  
    } catch (Exception e) {  
        e.printStackTrace();  
        throw new RuntimeException(e);  
    }  

}

猜你喜欢

转载自blog.csdn.net/hqbootstrap1/article/details/52065569
今日推荐