不多说,直接看代码:
package test; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class ListSort { public static void main(String[] args) { class User{ private int id; private String username; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } } List<User> list = new ArrayList<User>(); for(int i = 1; i < 5; i++) { User user = new User(); user.setId(i); user.setUsername("ldd"+i); list.add(user); } System.out.println("************排序前*************"); for(int i = 0; i < list.size(); i++) { System.out.println(list.get(i).getId() + "---" + list.get(i).getUsername()); } Collections.sort(list, new Comparator<User>() { @Override public int compare(User o1, User o2) { return (o2.getId()) - (o1.getId()); } }); System.out.println("************排序后*************"); for(int i = 0; i < list.size(); i++) { System.out.println(list.get(i).getId() + "---" + list.get(i).getUsername()); } } }
结果如下:
************排序前************* 1---ldd1 2---ldd2 3---ldd3 4---ldd4 ************排序后************* 4---ldd4 3---ldd3 2---ldd2 1---ldd1