[jdom-interest] Sorting a list of text elements
Ken Rune Helland
kenh at csc.no
Fri Mar 16 05:05:02 PST 2001
At 07:42 AM 3/16/2001 -0500, you wrote:
>Greetings:
>
>I am trying to sort a list of text elements within my servlet, which uses
>JDOM, for a pull down menu and am not getting it to work. Maybe I'm using
>the sort method (part of the Java 2 Collections framework)
>incorrectly. Here is the code snippet:
>
> //get root and all first level children (as List)
> Element root = doc.getRootElement();
> Element menuItems = root.getChild("Categories");
> List menuItem = menuItems.getChildren();
> Collections.sort(menuItem);
>
> out.println(" <td><SELECT NAME=\"category\">");
> for(int i=0;i<menuItem.size();i++){
> Element elem = (Element)menuItem.get(i);
> String menuItemText = elem.getTextTrim();
> out.println("<OPTION>"+menuItemText+"</OPTION>");
> }
>
> out.println(" </SELECT>");
>
>The Collections.sort(menuItem) line has no effect: the list is not sorted.
>I am expecting alphabetical sorting as the "natural order." Can someone
>point out what I need to do?
>
>Thanks, in advance,
>Bruce
Element does not implement the Comparable interace so it does not
have any "natural order". You must make a class that implements the
Comparator interface so it gives your wanted order and then call
Collections.sort(menuItem, myComparator);
KenR
More information about the jdom-interest
mailing list