This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes Sorting Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Sorting Problem" Watch "Sorting Problem" New topic
Author

Sorting Problem

parampreet sethi
Greenhorn

Joined: Aug 03, 2009
Posts: 27

Hi all,

Here goes the problem:

I have categories and multiple sub-categories inside each category.

Each category has a priority assigned to it. Thus the subcategories belonging to different categories should be sorted first in priority and if inside the same category they should be alphabetically sorted.

For Category priority sorting, I created a custom Comparator. I used TreeMap<String, TreeSet<String>> as data structure and passed the comparator while creating the object.

My first level priority sorting is working fine.

I have two issues:
1. The alphabetical ordering within a category is not working. This is because of issue #2.
2. When I try to do map.get(key), it always returns me null.



Is there any basic java concept that I am overlooking while coding this? Or other suggestions how this problem can be solved in a better/faster way.

Param
parampreet sethi
Greenhorn

Joined: Aug 03, 2009
Posts: 27

Thanks everyone. I got the issue.

In my Comparator I have combined the condition for > and = to return 1.

I changed it to separate conditions and returned 0 when the two objects are equal.

Suggestions on implementing this problem in a better way are welcome.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37907
    
  22
There are instructions for coding the methods in Comparable<T> and Comparator<T>, and the Collections Framework classes are programmed expecting those conditions to be fulfilled. If you choose to breach those conditions, you needn't expect the sorting to work as you hoped.
 
jQuery in Action, 2nd edition
 
subject: Sorting Problem
 
Similar Threads
TableSorter and Selection gives problems
Diff. Between Comparable & Comparator Interface
How to over ride the List.contains() method.
Sort a HashMap based on a Value object's attribute
HELP - Stuck on a TreeMap key problem