Rewrite the int compare(T o1, T o2) in Collections to sort the list instead of bubble sort

Sort the entire collection elements according to a certain attribute in the collection object

//重写Collections中的int compare(T o1, T o2)对list进行排序
public class Test01 {
    public static void main(String[] args) {
        User u1 = new User();
        User u2 = new User();
        User u3 = new User();
        User u4 = new User();
        u1.setId("23");
        u2.setId("13");
        u3.setId("3");
        u4.setId("22");
        // 新建一个List
        List<User> list = new ArrayList<>();
        list.add(u1);
        list.add(u2);
        list.add(u3);
        list.add(u4);
        System.out.println("排序前"+list);
        toSort(list);
        System.out.println("升序后"+list);
    }

    private static void toSort(List<User> list) {
        Collections.sort(list, new Comparator<User>() {
            @Override
            public int compare(User o1, User o2) {
                int i1 = Integer.parseInt(o1.getId());
                int i2 = Integer.parseInt(o2.getId());
                return (i1 - i2) < 0 ? -1 : 0;
            }
        });
    }

}

class User {
    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "User{" +
                "id='" + id + '\'' +
                '}';
    }
}
排序前[User{id='23'}, User{id='13'}, User{id='3'}, User{id='22'}]
升序后[User{id='3'}, User{id='13'}, User{id='22'}, User{id='23'}]

Note: When you want to print the list collection, remember to rewrite the toString() method in the entity class, otherwise the printed result is the address

排序前[com.sangeng.collection.User@30f39991, com.sangeng.collection.User@452b3a41, com.sangeng.collection.User@4a574795, com.sangeng.collection.User@f6f4d33]
升序后[com.sangeng.collection.User@4a574795, com.sangeng.collection.User@452b3a41, com.sangeng.collection.User@f6f4d33, com.sangeng.collection.User@30f39991]

Guess you like

Origin blog.csdn.net/m0_49128301/article/details/128556110