Connecting Tech Pros Worldwide Help | Site Map

put HashSets into one HashMap, why so difficult?

dlite922's Avatar
Expert
 
Join Date: Dec 2007
Location: Moon, Dark Side
Posts: 1,094
#1: May 19 '09
I could have this done in php in three lines of code but in Java here's what I need to do:

English
Looping through list of words I call a function that returns a HashSet of movie titles that contain that particular word. I want to insert these titles into a HashMap with their value being a counter of how many times this title occured.

(if two words return the same title, that title's value (counter) would be 2)

Relative Code:
Expand|Select|Wrap|Line Numbers
  1.  
  2. for(int i = 0; i < titleWords.length; i++ ) {
  3.             HashSet tempHash = (HashSet) hashtable.get( titleWords[i] );
  4.  
  5.             // put result into hashmap and increment counter
  6.             Iterator myIt = tempHash.iterator();
  7.             int counter;
  8.             while(myIt.hasNext()) {
  9.                 counter = 0;
  10.                 String title = (String) myIt.next();
  11.                 counter = (int) resultMap.get((String)myIt.next()); //*** ERROR: inconvertible types
  12.                 resultMap.put((String)myIt.next(), ++counter);
  13.             }
  14. }
  15.  
  16.  
  17.  
That's where it sits now, I tried a few different ways, and obviously they did not work.

Since I can't sort a HashMap, would something else work better? if so, don't bother answering my question with a HashMap, answer it with another list/array implementor that can store key/value pairs.

Thanks for any pointers,




Dan
dlite922's Avatar
Expert
 
Join Date: Dec 2007
Location: Moon, Dark Side
Posts: 1,094
#2: May 19 '09

re: put HashSets into one HashMap, why so difficult?


I solved this problem for now:

Expand|Select|Wrap|Line Numbers
  1. counter = ((Number) resultMap.get(title)).intValue() + 1;
  2.  
But how am I going to sort a hashmap? find some class online that sorts by value? There's got to be a better way.




Dan
Lives Here
 
Join Date: Sep 2006
Posts: 12,070
#3: May 20 '09

re: put HashSets into one HashMap, why so difficult?


Use generics. They will make your code cleaner because you won't need to have casts all over the place.
Read the API specs for TreeMap.
JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#4: May 20 '09

re: put HashSets into one HashMap, why so difficult?


Quote:

Originally Posted by dlite922 View Post

But how am I going to sort a hashmap? find some class online that sorts by value? There's got to be a better way.

TreeMaps are sorted maps and all maps can take another Map as a parameter for their constructor. It's a oneliner really.

btw, sorting a Map on their values doesn't make sense: values don't need to be unique and they are mainly a one way street data structure: key --> value.

kind regards,

Jos
Reply