Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

ArrayList sorting  RSS feed

 
Tom Lee
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
My question is regarding ArrayList sorting. Assume I have Employee object with two attributes 1.empName 2.empSalary. I have added 100 Employee objects in a Arraylist. Now I want to sort the arraylist according to empName. How would I achieve this?

Any help would be appreciated.

Thanks and Regards,
Tom Lee
 
Manuel Leiria
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Tom Lee:
Hi all,
My question is regarding ArrayList sorting. Assume I have Employee object with two attributes 1.empName 2.empSalary. I have added 100 Employee objects in a Arraylist. Now I want to sort the arraylist according to empName. How would I achieve this?

Any help would be appreciated.

Thanks and Regards,
Tom Lee


If you want to sort the Employee class only by empName, make your class implement the interface Comparable but if you want to use more then one criteria (e.g., first sort by empName and then sort by empSalary) you'll need two comparators. In this case, you must create two new classes and make them implement the interface Comparator.

Manuel Leiria
 
Tom Lee
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I want to sort the Employees by their names only. Can you explain me with help of any example/program ???

Thanks in advance,
Tom Lee
 
Manuel Leiria
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, so for a start, check the API

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Comparable.html

and then, check this tutorial,

http://www.onjava.com/pub/a/onjava/2003/03/12/java_comp.html
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!