Solved

Sorting/printing a hasmap in a particular order

Posted on 2007-03-25
15
368 Views
Last Modified: 2010-08-05
I am trying to sort the following data in my hash map from:
"JOHN", 26
"TERRY", 10
"ANDY", 5
"DAVID", 5
to:
"ANDY", 5
"DAVID", 5
"TERRY", 10
"JOHN", 26

Below is that code that has been used to make this work:

HashValueComparator comparator = new HashValueComparator(mymap);
TreeMap sortedMap = new TreeMap(comparator);
sortedMap.putAll(mymap);            
Object key = null;
for (Iterator i = sortedMap.keySet().iterator(); i.hasNext(); ) {
key = i.next();
System.out.println("Sorted: " + key + " => " + sortedMap.get(key));      
}

class HashValueComparator implements Comparator {
private Map map = null;
public HashValueComparator(Map map) {
setMap(map);
}
public void setMap(Map map) {
this.map = map;      
}
public int compare(Object o1, Object o2) {
Double DoubleA = (Double) map.get(o1);
Double DoubleB = (Double) map.get(o2);
int result = DoubleA.compareTo(DoubleB);
return result;
}
}

This works, however "DAVID", 5 overides "ANDY", 5, therefore I only get the 3 out 4 sorted elements.
Is there a way to correct this?
0
Comment
Question by:dr_alinaeem
  • 9
  • 4
  • 2
15 Comments
 
LVL 30

Expert Comment

by:Mayank S
ID: 18789046
HashMaps are not sorted because they store data based on the hash-codes of the keys. If you want to use sorting, use a list (sorted using Collections.sort ()) or a TreeSet
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 18789103
Ah noticed you have a TreeMap. What is the key and what is the value? Are the strings used as keys or the integers?
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 18789121
Maybe try:

List sortedKeys = Collections.sort ( Arrays.asList ( myMap.keySet ().toArray () ) ) ;

for ( int i = 0, count = sortedKeys.size () ; i < count ; i ++ )
{
  Object key = sortedKeys.get ( i ) ;
  System.out.println ( "Key: " + key + ", value: " + myMap.get ( key ) ) ;

}
0
Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

 

Author Comment

by:dr_alinaeem
ID: 18789162
i tried the way you told me and i get the following error:
cannot find symbol method sort

0
 
LVL 30

Expert Comment

by:Mayank S
ID: 18789299
0
 

Author Comment

by:dr_alinaeem
ID: 18789564
I have read this before,  I am still getting the same error, does it work on your machine?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 18789579
private static void sortHash() {
      Map<String, Integer> map = new HashMap<String, Integer>();
      map.put("JOHN", 26);
      map.put("TERRY", 10);
      map.put("ANDY", 5);
      map.put("DAVID", 5);
      
      List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
      Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) {
                  int result = e1.getValue() - e2.getValue();
                  return (result == 0)? e1.getKey().compareTo(e2.getKey()) : result;
            }
      });
      System.out.println(entries);
}
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 18789639
What is the code you used?
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 18789640
You're not using it the right way is all that can be said without seeing your code.
0
 

Author Comment

by:dr_alinaeem
ID: 18789651
List sortedKeys = Collections.sort(Arrays.asList(Segment_Result.keySet().toArray()));

for ( int i = 0, count = sortedKeys.size () ; i < count ; i ++ )
{
  Object key = sortedKeys.get ( i ) ;
  System.out.println ( "Key: " + key + ", value: " + Segment_Result.get ( key ) ) ;

}      
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 18789673
Sorry, sort () does not return anything. It sorts the list passed to it.
0
 
LVL 30

Accepted Solution

by:
Mayank S earned 60 total points
ID: 18789678
List<String> sortedKeys = Arrays.asList ( ( String[] ) Segment_Result.keySet().toArray ( new String[0] ) ) ;
Collections.sort ( sortedKeys ) ;

// or Collections.sort ( sortedKeys, new HashValueComparator () ) ;
0
 

Author Comment

by:dr_alinaeem
ID: 18789687
this works, however i need the lowest entry at the top, e.g. lowest value first
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 18789695
Use the Comparator which CEHJ posted instead of yours.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 18794546
>>this works, however i need the lowest entry at the top, e.g. lowest value first

Isn't that a contradiction in terms?

0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
eclipse formatting 6 87
servlet requestdispatcher include and forward differences 1 30
hibernate jars 4 28
How do I remove an object from a 3 23
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

786 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question