Collections能夠對List進行排序;spa
public static void main(String[] args) { List<User> list = new ArrayList<User>(); list.add(new User("zhangsan", 80)); list.add(new User("lisi", 88)); list.add(new User("wangwu", 60)); Collections.sort(list, new Comparator<User>() { public int compare(User user1, User user2) { /** * 升序排的話就是第一個參數.compareTo(第二個參數); * 降序排的話就是第二個參數.compareTo(第一個參數); */
return user1.getScore().compareTo(user2.getScore());//升序
} }); System.out.println(list); }
按字母排序code
public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("beijing"); list.add("shanghai"); list.add("hangzhou"); Collections.sort(list, new Comparator<String>() { public int compare(String str1, String str2) { //按首字母升序排 //return str1.compareTo(str2); //按第二個字母升序排
char c1 = str1.charAt(1); char c2 = str2.charAt(1); return c1-c2; } }); System.out.println(list); }