How to sort a List<> populated by java objects?

I have an entity

@Entity
public class User{
@Id
private int id;
private int score;
....
}


List<User> userlist=repo.findAll();

After I fetch it from database I want to sort it by score. I can sort from database but there will be some thing to do in code side.


Solution 1:

Collections.sort(userlist, Comparator.comparingInt(User::getScore));

or

userlist.sort(Comparator.comparing(User::getScore));

Solution 2:

Sorting through the database is more efficient. Why not use this functionality?

Anyways, to sort the list programmatically, you can use java streams:

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. In this case, the score. When the comparator returns a value > 0 that means that the current object is larger than the "next" object. If value = 0 then they are equal, if it is < 0 then it is smaller.

This is not the only way to do this. It can be done manually, through the Collections class, and so on.

Solution 3:

You can sort your data from the repository. It should look something like this:

interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByOrderByScoreDesc();
}

This will automatically generate the query for you. You can also use Asc instead of Desc if you want to change the order of sorting.

This is better than sorting from code, because you can also paginate this list, without getting all the data from your database.

You can check more details about this here.