[jdom-interest] Sorting a list of text elements

Gary Bentley gb at opengroup.org
Fri Mar 16 05:16:35 PST 2001

It's because the items returned by getChildren...i.e. Element, Comment
etc...do not implement the Comparable interface that the sort method uses.

Also, because the getChildren returns a list of objects that are NOT the
same, it means that doing a sort on these objects makes no sense.  You need
to pull out the actual information you want, probably in this case the text
within the elements named "menuitem" or whatever, put those into an array or
Collection container, like ArrayList and then sort...the String class does
implement the Comparable interface so sorting is possible.

So maybe change your code to say:

// Get all the children that are menuitems...
List menuitems = menuitems.getChildren ("menuitem");

// Create a new ArrayList to hold the items, remember that ArrayList is NOT
thread safe.
ArrayList items = new ArrayList ();

ListIterator menuitemsit = menuitems.listIterator ();

// Cycle over all the children for menu items...
while (menuitemsit.hasNext ())

    // Get the element which represents the menu item...this could also be
an attribute etc...
    Element menitem = (Element) menuitemsit.next ();

    // Get the text of the menu item..
    items.add (menitem.getTextTrim ());


// Sort the list...
Collections.sort (items);

  -----Original Message-----
  From: jdom-interest-admin at jdom.org [mailto:jdom-interest-admin at jdom.org]On
Behalf Of Bruce Altner
  Sent: Friday, March 16, 2001 12:42 PM
  To: jdom-interest at jdom.org
  Subject: [jdom-interest] Sorting a list of text elements


  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();

      out.println("       <td><SELECT NAME=\"category\">");
          Element elem = (Element)menuItem.get(i); 
          String menuItemText = elem.getTextTrim(); 
      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,

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://jdom.org/pipermail/jdom-interest/attachments/20010316/1272c145/attachment.htm

More information about the jdom-interest mailing list