Reputation: 21
I am doing an Access Control System and I have an ArrayList
of User
objects that contains a user number and other things. Here is a printed example of the list:
1;258;Pedro Pereira
2;3579;Pedro Miguens;A DEMO para LIC está pronta
9;391;João Silvério;Bem Vindo Criador
6;1234;joao
4;391;Miguel Fernandes;Telefonar ao João Manuel
How do I sort the ArrayList
so that the userList
is ordered without having to write the full code?
Upvotes: 0
Views: 239
Reputation: 1096
You need to implement Comparable interface for your user class and implement its compareTo
method. You have option to choose which field or combination of fields you want to be as your key for sorting.
Next whenever you want to sort your list, you can use Collection.sort(userList)
.
Upvotes: 0
Reputation: 9155
In Java 8, it could be something like:
Collections.sort(userList, (user1, user2) -> user1.getId() - user2.getId());
assuming you have an ArrayList
of User
beans called userList
, each with a property called id
.
Upvotes: 2