实体类
package com.wgjn.modules.cms.entity;
public class User {
private String username;
private String age;
public User(String username, String age) {
this.username = username;
this.age = age;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
主体
package com.wgjn.modules.cms.controller;
import com.wgjn.modules.cms.entity.User;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class cesi {
public static void main(String[] args) {
List<User> list = new ArrayList<User>();
list.add(new User("张三", "gd5"));
list.add(new User("李四", "30465JK"));
list.add(new User("王五", "464FG"));
list.add(new User("陈十七", "DG454GS")); // 陈十七永远十七岁
Collections.sort(list, new Comparator<User>() {
@Override
public int compare(User u1, User u2) {
int diff = getNum(u1.getAge()) - getNum(u2.getAge());
if (diff > 0) {
return -1;
} else if (diff < 0) {
return 1;
}
return 0; //相等为0
}
}); // 按年龄排序
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getAge());
}
}
static int getNum(String c) {
String str = c;
str = str.trim();
String str2 = "";
if (str != null && !"".equals(str)) {
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) >= 48 && str.charAt(i) <= 57) {
str2 += str.charAt(i);
}
}
}
return Integer.parseInt(str2);
}
}