最近工作中遇到对list排序的问题,使用Collection.sort()
下边是我自己做的练习,记录下package com.junit.test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
public class CollectionsTest {
public static void main(String[] args) {
CollectionsTest c = new CollectionsTest();
List stList = new ArrayList();
Student s1 = c.new Student();
s1.setAge("33");
s1.setName("groupB");
s1.setSex("nan4");
Student s5 = c.new Student();
s5.setAge("77");
s5.setName("groupB");
s5.setSex("nan4");
Student s2 = c.new Student();
s2.setAge("22");
s2.setName("groupC");
s2.setSex("nan1");
Student s3 = c.new Student();
s3.setAge("13");
s3.setName("groupA");
s3.setSex("nan2");
Student s4 = c.new Student();
s4.setAge("17");
s4.setName("groupG");
s4.setSex("nan6");
stList.add(s1);
stList.add(s2);
stList.add(s3);
stList.add(s4);
stList.add(s5);
Iterator iter = stList.iterator();
while(iter.hasNext()){
Student st = (Student)iter.next();
System.out.println(st.getName()+" "+st.getAge()+" " +st.getSex());
}
System.out.println("---------------------------------------------");
Collections.sort(stList, c.new Compartor1());
Iterator iter1 = stList.iterator();
while(iter1.hasNext()){
Student st1 = (Student)iter1.next();
System.out.println(st1.getName()+" "+st1.getAge()+" " +st1.getSex());
}
}
public class Compartor1 implements Comparator{
public int compare(Student o1, Student o2) {
String name1 = o1.getName();
String name2 = o2.getName();
//先按name升序
if(name1.compareTo(name2)>0){
return 1;
}else if(name1.compareTo(name2)<0){
return -1;
}
else{
//再按age降序排列
String age1 = o1.getAge();
String age2 = o2.getAge();
if(age1.compareTo(age2)>0){
return -1;
}else if(age1.compareTo(age2)<0){
return 1;
}
}
return 0;
}
}
public class Student{
public String name;
public String age;
public String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
}