Java 8 – customised sort based on specific order

  • A+

I would like to sort the user list based on their status but the order must be based on the order that I set.

I want to set the order of list,

The order should be 1, 0 , 5. We should also keep in mind to order the username as well.

List<User> users = new ArrayList();          users.add(new User("A", 1));          users.add(new User("B", 5));          users.add(new User("C", 0));          users.add(new User("D", 1));          users.add(new User("E", 5));          users.add(new User("F", 0)); 

Here's the user class

public class User {          private String username;          private Integer status;      } 

It should look like this

[     {       "username": "A",       "status": 1     },     {        "username": "D",        "status": 1     },     {        "username": "C",        "status": 0     },     {        "username": "F",        "status": 0     },     {        "username": "B",        "status": 5     },     {        "username": "E",        "status": 5     } ] 

I not sure if it's possible to use Comparator.comparing, since this one is neither ascending nor descending order.


If you don't mind using Guava in your project, you can use Ordering.explicit:

users.sort(Ordering.explicit(1, 0, 5).onResultOf(User::getStatus)); 

If you want to sort by name also, then add thenComparing:

users.sort(Ordering         .explicit(1, 0, 5)         .onResultOf(User::getStatus)         .thenComparing(User::getUsername)); 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: