sorting - Sort java map by value (which contains a set) -


i have map looks

map<word, set<word>> tuplemap = new hashmap<word, set<word>>();

the word class nothing special, contains few strings value , on. trying sort map number of elements of associated set. word has words associated first/last in map.

i did manage sort map key using code:

wordmapcomparator bvc = new wordmapcomparator(tuplemap); treemap<word, set<word>> sortedtuplemap = new treemap<word, set<word>>(bvc);     sortedtuplemap.putall(tuplemap); ` 

where comparator is

class wordmapcomparator implements comparator<word> {      map<word, set<word>> base;      public wordmapcomparator(map<word, set<word>> tuplemap) {         this.base = tuplemap;     }      public int compare(word a, word b) {         return a.getvalue().compareto(b.getvalue());     } } 

now works fine, map gets sorted based on words value. however, tried comparator:

class wordmapcomparator implements comparator<word> {      map<word, set<word>> base;      public wordmapcomparator(map<word, set<word>> tuplemap) {         this.base = tuplemap;     }      public int compare(word a, word b) {         return base.get(a).size() >= base.get(b).size() ? -1 : 1;     } } 

and testing resulting map with

    1. for(word w : sortedtuplemap.keyset()){     2.  system.out.print(w.getvalue() + " : ");     3.  for(word wo : sortedtuplemap.get(w)){     4.      system.out.print(wo.getvalue() + " ");     5.  }     6.  system.out.println();     7. }     

i null pointer exception @ line 3, basically, resulting set null.

why happen, , moreover, how can fixed?

thanks million!

return base.get(a).size() >= base.get(b).size() ? -1 : 1; 

this wrong: if number of words same, should return 0, not 1 or -1 depending on how , b compared. use

return integer.compare(base.get(a).size(), base.get(b).size()); 

that, however, make map consider words same amount of associated words equal, need distinguish them criterion:

int result = integer.compare(base.get(a).size(), base.get(b).size()); if (result == 0) {     result = a.compareto(b); } return result; 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -