Skip to content
Advertisement

Java sort list alphabeticaly with value “Other” at the end

I got a small Spring Boot application that manages some projects and clients.
A client has a country ( which is an entity) and I want to let the user when he wants to create/update his clients to chose from a predifined country picklist in the UI.
If the country is not present in the list, the user should chose “Other” untill a new country will be added by the admin.
The only problem is that this “Other” value must be always at the end of the pick list and the rest of the countries should be sorted alphabetically. If I sort the list alphabetically the value “Other” will be somewhere at the middle.
How can I manage to do this efficiently (both Java and DB) ?
I am using for now JPA repository findAll for countries.
One first ideea was to add an index to each country and put “Other” with a big value so I will sort by index. But if an insert is done….I dont know how to update the other values.

EDIT:
Jens Schauder Solution worked !

Advertisement

Answer

Add a ordering column, I call it sortorder for now. Fill it with 0 by default and with 999 for the special “Other” country.

Then order by sortorder and country name.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement