Data sorting problem

This article describes a few simple examples of data sorting during development. The following examples all take the reverse order of creation time as an example. You can replace them when you use them.

Database layer

1-sql

SELECT * from question_type ORDER BY id desc;

2-mybatis

example.setOrderByClDFFause("create_time desc") //倒序

Code level (java):

Below 1-jdk8

Collections.sort(list, new Comparator<TUser>() {
            @Override
            public int compare(TUser o1, TUser o2) {
                return o2.getId() - o1.getId();
            }
        }); //不用赋值

2-jdk8 and above

userList = userList.stream().sorted(Comparator.comparing(TUser::getCreateTime).reversed()).collect(Collectors.toList())
//需要赋值或者直接返回,reversed()表倒序
//函数式编程
list.sort((o1,o2) -> o2.getId() - o1.getId());
//多条件
list.sort(Comparator.comparing(TUser::getId)
        .thenComparing(
                (o1,o2)-> o2.getId() - o1.getId()
        ));

Conclusion

Hope this article can be useful to you, welcome to like, comment and share.

Guess you like

Origin blog.csdn.net/weixin_41589363/article/details/108995295