I have records in the database with the sort order number. Now I want to create a UI with buttons UP and DOWN to reorder them. What is the best algorithm to make two functionsUp(record) and functionDown(record) in order to rearrange them by changing orderNum and them persist that number to the database.
Here is the example of what I’m trying to achieve (before foo=24, after foo=25):
Before pressing up on bar
id | name | orderNum
--------------------
1 | foo | 24
2 | bar | 25
3 | doe | 26
After
id | name | orderNum
--------------------
1 | foo | 25
2 | bar | 24
3 | doe | 26
Assuming that you are using Java Collections, you can write a class that implements
Comparableand use the utilityCollections.sort(). More info about ordering colletions here.