ArrayList 数据根据某字段排序

package com.changxuan.sort;

import com.changxuan.domain.Human;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 * @Author: ChangXuan
 * @Decription: 测试List排序
 **/
public class Test {
    public static void main(String[] args){
        ArrayList<Human> humans = new ArrayList<>(4);
        humans.add(new Human("lihua","male", 5));
        humans.add(new Human("xiaofang","female", 2));
        humans.add(new Human("daming","male", 7));
        humans.add(new Human("xiaogang","male", 1));

        System.out.println("排序之前:");
        for(Human itemHuman : humans){
            System.out.println(itemHuman.toString());
        }

        // 进行排序
        Collections.sort(humans, new Comparator<Human>() {
            @Override
            public int compare(Human before, Human after) {
                //按照用户定义的字段Age升序排列
                return before.getAge().compareTo(after.getAge());
            }
        });

        System.out.println("排序完成:");
        for(Human itemHuman : humans){
            System.out.println(itemHuman.toString());
        }


    }
}
package com.changxuan.domain;

/**
 * @Author: ChangXuan
 * @Decription: 人
 **/
public class Human {
    public Human(String name, String gender, Integer age) {
        this.name = name;
        this.gender = gender;
        this.age = age;
    }

    private String name;

    private String gender;

    private Integer age;

    public String getName() {
        return name;
    }

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

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

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

发布者

Avatar photo

常轩

总要做点什么吧!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注