This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I have a question on sorting of lists. I have 3 list objects objList1, objList2 and objList3 and each of these objects contain a Name field. I need to sort these lists each in ascending order of Name. I am using a Bean Comparator for this prpose with the following logic, BeanComparator comp = new BeanComparator(ATTRIBUTE_TO_BE_SORTED); Collections.sort(objList1, comp); Collections.sort(objList2, comp); Collections.sort(objList3, comp); This works fine but since Bean Comparator is used on the Webserver and I need to do this on my App server, I need another way to sort the lists. Can you please make a suggestion.
Have your bean implement java.lang.Comparable. Then you can call Collections.sort() without a Comparator. What you should do is copy the jakarta commons bean utils jar file to your app server so you can use BeanComparator. Being consistent in coding is essential to writing a maintainable application, and reuse is one of the fundamental building blocks of object oriented programming.
That seems to be an odd restriction, but I suppose you could use the sort() method from Arrays, assuming the sorted objects are Strings. You'll have to do some jiggery-pokery--extract the names into an array, sort them, build new Lists and read the elements into them in sorted order using the sorted array as your guide--but it would work.
The reason comparators are the natural thing to use here is that the objects you're sorting probably have no natural ordering, or if they do, they have a natural ordering different from the ordering you want. I really don't see a way to do what you want in a natural way without using comparators.
Joined: Apr 16, 2001
I'd forgotten about implementing Comparable, which saves you the trouble of writing your own Comparator. But you have to implement the compareTo() method in either case. Joe's suggestion is strongly preferable to writing your own Comparator, assuming the objects to be sorted are always sorted in the same way.