Collections.sort()排序代码案例

2020/2/16 17:55:07 人评论 次浏览 分类:学习教程

1、案例:

Person对象(名字,id,年龄)

要求按照,年龄从小到大排序,年龄相等,按照名字的字典顺序de倒序排序

2、案例设计:

     1)使用ArrayList存储Person对象,

      2)利用Collections.sort()进行排序

      3)输出结果

3、代码分享:

package CollectionDemo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Comparator;
class Person{
    private int id;
    private int age;
    private String name;

    public Person(int id, int age,String name){
        this.id=id;
        this.age=age;
        this.name=name;
    }
    public void setId(int id) {
        this.id = id;
    }

    public void setAge(int age) {
        this.age = age;
    }
    public void setName(String name){
        this.name=name;
    }

    public int getId() {
        return id;
    }

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

public class CollectionDemo2 {
    public static void main(String[] args){
        List<Person> arrayList =new ArrayList<>();
        arrayList.add(new Person(001,20,"yang"));
        arrayList.add(new Person(002,20,"zhang"));
        arrayList.add(new Person(003,30,"li"));
        arrayList.add(new Person(004,40,"Coco"));
        arrayList.add(new Person(005,40,"Marry"));
        Collections.sort(arrayList,new Comparator<Person>(){
            public int compare(Person o1,Person o2){
                if(o1.getAge()!=o2.getAge()){
                    return o1.getAge()-o2.getAge();//按照年龄升序排序
                }else{
                    return o2.getName().compareToIgnoreCase(o1.getName());//按照名字的字典顺序倒序排序
                }
            }
        });
        //输出
        for(Person p:arrayList){
            System.out.println(p);
        }






    }
}

 

输出:

Person{id=2, age=20, name='zhang'}
Person{id=1, age=20, name='yang'}
Person{id=3, age=30, name='li'}
Person{id=5, age=40, name='Marry'}
Person{id=4, age=40, name='Coco'}

 

 

进进进出出
发布了45 篇原创文章 · 获赞 8 · 访问量 5814
私信 关注

相关资讯

    暂无相关的资讯...

共有访客发表了评论 网友评论

验证码: 看不清楚?
    -->