Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 923
MichaelMcCabe Avatar asked Dec 10 '22 16:12

MichaelMcCabe


2 Answers

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.

like image 112
Jack Avatar answered Mar 26 '23 15:03

Jack


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

like image 36
Yishai Avatar answered Mar 26 '23 13:03

Yishai