[英]How to use Collections in java to sort list populated from a class
[英]How to sort a List<> populated by java objects?
我有一个实体
@Entity
public class User{
@Id
private int id;
private int score;
....
}
List<User> userlist=repo.findAll();
从数据库中获取它后,我想按score
对其进行排序。 我可以从数据库中排序,但在代码方面会有一些事情要做。
Collections.sort(userlist, Comparator.comparingInt(User::getScore));
或者
userlist.sort(Comparator.comparing(User::getScore));
对数据库进行排序更有效。 为什么不使用这个功能?
无论如何,要以编程方式对列表进行排序,您可以使用 java 流:
List<User> userList=repo.findAll();
List<User> sortedList = userList.stream().sorted((o1, o2) ->
{
return Integer.compare(o1.getScore(), o2.getScore());
}).collect(Collectors.toList());
You turn the list into a stream and then use the comparator function (the lambda in there) to compare whatever you want in your User
object. 在这种情况下,得分。 当比较器返回值 > 0 时,表示当前 object 大于“下一个” object。 如果 value = 0 则它们相等,如果它 < 0 则它们更小。
这不是唯一的方法。 可以通过Collections
class 等手动完成。
在存储库中,您可以定义 findByOrderByScoreDesc() 或 findByOrderByScoreAsc() 方法以通过对分数值进行排序来获取结果。 或者在获得结果后,您可以对 Collection 应用排序。 如果您想使用 Pageable 来获取结果,那么在创建 Pageable 对象时,您可以指定排序顺序和排序字段。
您可以对存储库中的数据进行排序。 它应该看起来像这样:
interface UserRepository extends JpaRepository<User, Long> {
List<User> findByOrderByScoreDesc();
}
这将自动为您生成查询。 如果要更改排序顺序,也可以使用 Asc 而不是 Desc。
这比从代码中排序要好,因为您也可以对这个列表进行分页,而无需从数据库中获取所有数据。
您可以在此处查看有关此内容的更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.