MichaelMcCabe MichaelMcCabe - 5 months ago 20
Java Question

Getting a java collection of objects in Alphabetical order

I have a question that I dont really know where to start. So I thought i'd ask it here.

Basically, I have a drop down with names in it. I want these names to be in alphabetical order.

Populating the drop down happens as follows;

I query a database and pull down an Id and Name, make a object called "UserList", and set the name and id variables with what I get back.
I then add this object to an ArrayList. I do this over and over.

I then convert this collection to an array, and pass it to my JSP page using

session.setAttribute("userList", UserList);

I then populate the drop down as below.

<c:forEach items="${userList}" var="c" >
`<html-el:option value="${c.id}"><c:out value="${c.name}"/></html-el:option> </c:forEach>

There probably is a simple answer but how to I sort these names?


Michael, you should be using a join and an order by to get this data from the database, not retrieving and sorting in Java:

 select person.id, person.name from person inner join person_company using(personid)
 order by person.name;

And not trying to sort and do this in java (the syntax above may not be perfect, my MySQL's a bit rusty).