java ArrayList数据对象按排序值大小排序

时间:2025-01-26 08:30:30

QQ群:372135639

import ;
import ;
import ;
import ;
import ;

/**
 * 
 * @author 
 *
 */
public class ListSort {

    public static void main(String[] args) {
        List<User> users = new ArrayList<User>();
        int id = 0;
        User user = null;

        Random random = new Random();

        id = (100000);
        user = new User(id);
        (id);
        (user);

        id = (100000);
        user = new User(id);
        (id);
        (user);

        id = (100000);
        user = new User(id);
        (id);
        (user);

        id = (100000);
        user = new User(id);
        (id);
        (user);

        id = (100000);
        user = new User(id);
        (id);
        (user);

        id = (100000);
        user = new User(id);
        (id);
        (user);

        id = (100000);
        user = new User(id);
        (id);
        (user);

        id = (100000);
        user = new User(id);
        (id);
        (user);

        id = (100000);
        user = new User(id);
        (id);
        (user);

        ("Before sort:");
        for (User _user : users) {
            (_user + " ");
        }

        (users, new Comparator<User>() {
            @Override
            public int compare(User user1, User user2) {
                Integer id1 = ();
                Integer id2 = ();
                                  //可以按User对象的其他属性排序,只要属性支持compareTo方法
                return (id1);
            }
        });
        ("\nAfter sort 从大到小倒序:");
        for (User _user : users) {
            (_user + " ");
        }

        (users, new Comparator<User>() {
            @Override
            public int compare(User user1, User user2) {
                Integer id1 = ();
                Integer id2 = ();
                                //可以按User对象的其他属性排序,只要属性支持compareTo方法
                return (id2);
            }
        });
        ("\nAfter sort 从小到大正序:");
        for (User _user : users) {
            (_user + " ");
        }
    }

}

class User {
    private int id;

    public User(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return id + "";
    }
}
程序运行输出结果:

Before sort:
49459 73363 18294 65350 36522 77535 38273 58512 34980 
After sort 倒序:
77535 73363 65350 58512 49459 38273 36522 34980 18294 
After sort 正序:
18294 34980 36522 38273 49459 58512 65350 73363 77535 

相关文章