Collections.sort()的使用
1.實現Comparable接口(如果List<Object>中Object實現了Comparator接口,便可以直接用以下Collections.sort的方式對List進行排序)
public class Test {
?public static void main(String[] args) {
??List<User> userList = new ArrayList<User>();
??userList.add(new User(3, "3"));
??userList.add(new User(2, "2"));
??userList.add(new User(5, "5"));
??userList.add(new User(7, "7"));
??Collections.sort(userList);
??for (User user : userList) {
???System.out.println(user.getAge());
??}
?}
}
class User implements Comparable<User> {
?private int age;
?private String name;
?public User(int age, String name) {
??super();
??this.age = age;
??this.name = name;
?}
?public int getAge() {
??return age;
?}
?public void setAge(int age) {
??this.age = age;
?}
?public String getName() {
??return name;
?}
?public void setName(String name) {
??this.name = name;
?}
?@Override
?public int compareTo(User user) {
??return age - user.getAge();
?}
}
2.實現Comparator接口
public class Test {
?public static void main(String[] args) {
??List<User> userList = new ArrayList<User>();
??userList.add(new User(3, "3"));
??userList.add(new User(2, "2"));
??userList.add(new User(5, "5"));
??userList.add(new User(7, "7"));
??Collections.sort(userList,new CompareUser());
??for (User user : userList) {
???System.out.println(user.getAge());
??}
?}
}
class CompareUser implements Comparator<Object>{
?@Override
?public int compare(Object arg0, Object arg1) {
??User user1=(User)arg0;
??User user2=(User)arg1;
??return user1.getName().toLowerCase().compareTo(user2.getName().toLowerCase());
?}
?
}
class User?? {
?private int age;
?private String name;
?public User(int age, String name) {
??super();
??this.age = age;
??this.name = name;
?}
?public int getAge() {
??return age;
?}
?public void setAge(int age) {
??this.age = age;
?}
?public String getName() {
??return name;
?}
?public void setName(String name) {
??this.name = name;
?}
}
轉載于:https://blog.51cto.com/5618698/1627229
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的Collections.sort()的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode - Reverse B
- 下一篇: 微信在公众号增开了新广告位 这次是在图文