Java – sort F: selectitems list based on tags
•
Java
I have a list of selectitem values and tags The data is obtained from the database. The selectitem list has the following values:
<1,100-500> <2,1000-1500> <3,500-1000>
Here, 1, 2 and 3 are the values of the selectitem list, and '100-500', '1000-1500' and '500-1000' are the labels respectively As you can see, the list is sorted by label However, my requirement is that the list should be displayed in the drop-down list as follows:
100-500 500-1000 1000-1500
Can someone suggest a solution?
Solution
If you cannot modify the code that gets the selectitem instance from the DB to sort according to your preference, you must sort them yourself:
// this gets you a list which is not sorted as you would like
List<SelectItem> list = getMasterValues("Staff Range");
// you need to sort the list before displaying it.
// To sort the list,you need a Comparator which will tell the sorting
// algorithm how to order the items
Comparator<SelectItem> comparator = new Comparator<SelectItem>() {
@Override
public int compare(SelectItem s1,SelectItem s2) {
// the items must be compared based on their value (assuming String or Integer value here)
return s1.getValue().compareTo(s2.getValue());
}
};
// Now that you have the comparator,sort the list using it :
Collections.sort(list,comparator);
// and Now iterate over the list to display it :
for (SelectItem item : list) {
System.out.println("value = " + item.getValue() + "; label = " + item.getLabel());
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
