0

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?

riddle_me_this
  • 8,575
  • 10
  • 55
  • 80
  • 1
    What is a user? What do you want to order by? What full code? – shmosel Dec 14 '16 at 00:18
  • Possible duplicate of [Sort an ArrayList based on an object field](http://stackoverflow.com/questions/4066538/sort-an-arraylist-based-on-an-object-field) – Tom Dec 14 '16 at 01:19

2 Answers2

2

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.

riddle_me_this
  • 8,575
  • 10
  • 55
  • 80
0

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).

Mehdi
  • 746
  • 1
  • 10
  • 25