voyent
How to sort a selectItem?  XML
Forum Index -> General Help
Author Message
elecdesa

Joined: 28/Nov/2007 00:00:00
Messages: 28
Offline


Hi.

My question is more related with java but...

I want to make a copy of a selecItem variable and sort it by one of its fields.

I retrieve the values from the database order by ID like this:
(ID, Description)

but once I have it like this, sometimes I want to create a new one and order it by description but without make the query against database again.

ArrayList arrayList = new ArrayList();
loop
SelectItem item = new SelectItem();

item.setValue(result.getString("ID"));
item.setLabel(result.getString("Description"));
arrayList.add(item);
end loop

This array is sorted by ID, but how I create a new one order by Description (do I need to create my quicksort method??).

Any help??
Thanks
paulvr

Joined: 12/May/2008 00:00:00
Messages: 121
Offline


Add the items to a TreeMap<String, Integer>instead an ArrayList, with the String holding the description and the Integer holding the ID.
[Email]
qpid

Joined: 09/Nov/2007 00:00:00
Messages: 21
Offline


I prefer the BeanComperator from the apache commons project:
http://commons.apache.org/beanutils/apidocs/org/apache/commons/beanutils/package-summary.html#collections

create the list, fill it with your beans and than sort it with the Collections.sort(list, beanComparator) method

run over the list and create your selectItems...

pay attention to null values on the sorted property in the beans

Code:
 public class NullSafeBeanComparator extends BeanComparator {
 
 	public NullSafeBeanComparator(String property) {
 		super(property, new NullComparator());
 	}
 
 	public int compare(Object o1, Object o2) {
 		if (getProperty() == null) {
 			// compare the actual objects
 			return getComparator().compare(o1, o2);
 		}
 
 		try {
 			Object value1 = null;
 			Object value2 = null;
 			try {
 				value1 = PropertyUtils.getProperty(o1, getProperty());
 			} catch (NestedNullException e) {
 			}
 
 			try {
 				value2 = PropertyUtils.getProperty(o2, getProperty());
 			} catch (NestedNullException e) {
 			}
 
 			return getComparator().compare(value1, value2);
 		} catch (Exception e) {
 			throw new ClassCastException(e.toString());
 		}
 	}
 }


regards qpid
elecdesa

Joined: 28/Nov/2007 00:00:00
Messages: 28
Offline


Hi,
thanks both for your replies.

I'm using the arrayList because later I convert it to a selectItem. I use a method found in component-showcase :

public SelectItem[] arrayList2SelectItem(ArrayList<SelectItem> arrayList) {
SelectItem[] result = new SelectItem[arrayList.size()];
arrayList.toArray(result);
return result;
}


The idea is to sort the selectItem because in the application I have no more the arrayList, just the selectItem and not always I need to sort the selectItem.

best regards



 
Forum Index -> General Help
Go to:   
Powered by JForum 2.1.7ice © JForum Team