关于Collections中sort方法排序

public class Test {
String name;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Test() {
super();
// TODO Auto-generated constructor stub
}
public Test(String name, int age) {
super();
this.name = name;
this.age = age;
}

public static void main(String[] args) {
    List<Test> list = new ArrayList<>();
    list.add(new Test("a",1));
    list.add(new Test("c",2));
    list.add(new Test("d",3));
    list.add(new Test("b",4));
    for (Test test : list) {
        System.out.println(test.getName()+"--"+test.getAge());
    }

    System.out.println("\n");
    System.out.println("按name排序");
    Collections.sort(list,new Comparator<Test>(){
        @Override
        public int compare(Test o1, Test o2) {
            return    o1.getName().compareTo(o2.getName());
        }}
    );
    for (Test test : list) {
        System.out.println(test.getName()+"--"+test.getAge());
    }

    System.out.println("\n");
    System.out.println("按age排序");
    Collections.sort(list,new Comparator<Test>(){
        @Override
        public int compare(Test o1, Test o2) {
            //compareTo为包装类型的方法,需要将int转换为包装类型
            return    (new Integer(o1.getAge())).compareTo(o2.getAge());
        }}
    );
    for (Test test : list) {
        System.out.println(test.getName()+"--"+test.getAge());
    }

}

}

jdk1.8又优化了sort方法,特意去百度了一下
此为老版string类型排序:
List names = Arrays.asList(“peter”, “anna”, “mike”, “xenia”);
Collections.sort(names, new Comparator() {
@Override
public int compare(String a, String b) {
return b.compareTo(a);
}
});
Java 8提供了更简洁的语法,lambda表达式:
Collections.sort(names, (String a, String b) -> {
return b.compareTo(a);
});

猜你喜欢

转载自blog.csdn.net/qq_33157669/article/details/81541073