package com.asic.demo;
import java.util.*;
public class Day01 {
public static List<User> initNewlistUser() {
List<User> list = new ArrayList<User>();
Random ra = new Random();
for (int i = 0; i < 10; i++) {
User user = new User();
user.setId(i);
user.setName("zhangsan" + i);
user.setAge(ra.nextInt(100) + 1);
list.add(user);
}
return list;
}
/**
* 根据list里面的对象的属性进行排序 升序排列
*
* @param list
*/
public static void sortList(List list) {
Collections.sort(list, new Comparator<User>() {
@Override
public int compare(User o1, User o2) {
int a = o1.getAge();
int b = o2.getAge();
System.out.println("a=" + a + " b=" + b + " " + o1.getAge().compareTo(o2.getAge()));
//TODO: 升序排列
return o1.getAge().compareTo(o2.getAge());
//TODO: 降序排列
//return o2.getAge().compareTo(o1.getAge());
}
});
}
public static void main(String[] args) {
List<User> list = initNewlistUser();
System.out.println("===========排序之前===========");
for (User u : list) {
System.out.println(u);
}
sortList(list);
System.out.println("===========排序之后===========");
for (User u : list) {
System.out.println(u);
}
}
}
class User {
private Integer id;
private Integer age;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
'}';
}
}