views:

119

answers:

7

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?

A: 

You can try and override the compareTo method for UserList so that it compares the elements in an alphabetical way according to some string value. Then, call the sort method of the array list and it should sort them using the compareTo you overrode.

npinti
+7  A: 

You usually do it by invoking public static Collections.sort(List<T> list) with your ArrayList as the parameter, but take care to implement the Comparable interface or it won't work (if they are Strings then it's already implemented):

Collections.sort(yourList);

Otherwise if you have a custom class but you want to sort just over some string field inside you can delegate the compareTo method:

public class User implements Comparable<User>
{
  public int compareTo(User other)
  {
    return userName.compareTo(other.userName);
  }
}

Finally if noone is your case just roll your own compareTo method, it should return -1, 0 or 1 if the the calling object is less, equal to or greater than the passed one.

Jack
I'll give the custom class a go, as I assume that Collections.sort, wouldnt work with the arrayList containing objects of type string AND int
MichaelMcCabe
@Michael: it **IS** already a custom class! It has at least `id` and `name` properties ;) Is this all your own code or do you have to maintain an existing project?
BalusC
Extending an existing project... as you can probably tell :PI wasnt aware you meant implementing Comparable on the exsiting class. I'm giving this a go for learning purposes, but for this particular problem I'm gonna do it from a DB query like suggested above
MichaelMcCabe
thx balus for fixing that code, I was just too lazy and copied/pasted it :)
Jack
A: 

You should use Collections.sort and either of
1) Make your User class implement Comparable interface
2) Create a UserListComparator implementing Comparator<UserList> interface
See Comparable interface documentation for details

Nikolay Ivanov
+1  A: 

I think the most ideal solution to this problem is to sort them at the database query level. If the table is well indexed, this will be the fastest and arguable the "best" practice.

That being said, if you just want to sort that list and not start mucking on the database side, use Collections.sort and have your UserList implement Comparable<UserList>

Be careful to use the case insensitive string comparison, or your users will likely not appreciate the sorting results.

Yishai
+1  A: 

I would change the database query to return the rows in the order you want them.

If you are using SQL the query could look like the following.

SELECT Id, Name FROM Person ORDER BY Name;

This has some advantages over doing it in code.

  • It is faster.
  • You do not have to change your code.
  • It is less work.
Julian Lettner
This wouldnt work (forgive me if i'm wrong) with the way I am querying.I am iterating over an array of integers being used by my query. i.e.SELECT Id, NAME FROM Person WHERE id='"+variable+"';every query i make, I add a object to my ArrayList
MichaelMcCabe
So the ORDER BY, would be pointless due to only one record coming back per query
MichaelMcCabe
@Michael, that is a terrible way to query the database. For any non-trivial amount of records it will be very slow. Instead use: Select id, name from person where id in (variable, variable, variable) order by name. And where are you getting this list of Id's from? If from the database, you should query it all out of the database in one go.
Yishai
The list of Id's come from the database but from a seperate table. I have a user_company table in which I pass a company id (column 1) and retreive the user id's from the relevent rows. I then use those id's to query a user table to retreive their names. So I guess, off topic from this question. What would be a more simple mysql query to do this? My entire database/mysql knowledge is primative
MichaelMcCabe
I agree with Yishai. Edit:Just join the tables! Information about this can be found here: http://www.w3schools.com/sql/sql_join.aspYou may also want to read more about SQL in general.
Julian Lettner
@Michael, I'm going to add another answer to address this because it too much for a comment.
Yishai
+2  A: 

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).

Yishai
@Yishai, I have to be honest, I dont know how I missed the concept of inner join. This is a schema I jumped ontop of and thats probably why. But its SO much cleaner and easier so thanks for showing me!! I did the followingSELECT company.id, company.name from company INNER JOIN user_company ON company_id = user_company.CompanyId WHERE user_company.UserId='UserIDVariable' ORDER BY name;
MichaelMcCabe
A: 
Gala101