浅谈Java之Map 按值排序 (Map sort by value)
Map是键值对的集合,又叫作字典或关联数组等,是最常见的数据结构之一。在java如何让一个map按value排序呢?看似简单,但却不容易!
比如,Map中key是String类型,表示一个单词,而value是int型,表示该单词出现的次数,现在我们想要按照单词出现的次数来排序:
Mapmap=newTreeMap(); map.put("me",1000); map.put("and",4000); map.put("you",3000); map.put("food",10000); map.put("hungry",5000); map.put("later",6000);
按值排序的结果应该是:
keyvalue me1000 you3000 and4000 hungry5000 later6000 food10000
首先,不能采用SortedMap结构,因为SortedMap是按键排序的Map,而不是按值排序的Map,我们要的是按值排序的Map。
Couldn'tyoudothiswithaSortedMap?
No,becausethemaparebeingsortedbyitskeys.
方法一:
如下Java代码:
importjava.util.Iterator; importjava.util.Set; importjava.util.TreeSet; publicclassMain{ publicstaticvoidmain(String[]args){ Setset=newTreeSet(); set.add(newPair("me","1000")); set.add(newPair("and","4000")); set.add(newPair("you","3000")); set.add(newPair("food","10000")); set.add(newPair("hungry","5000")); set.add(newPair("later","6000")); set.add(newPair("myself","1000")); for(Iteratori=set.iterator();i.hasNext();) System.out.println(i.next()); } } classPairimplementsComparable{ privatefinalStringname; privatefinalintnumber; publicPair(Stringname,intnumber){ this.name=name; this.number=number; } publicPair(Stringname,Stringnumber)throwsNumberFormatException{ this.name=name; this.number=Integer.parseInt(number); } publicintcompareTo(Objecto){ if(oinstanceofPair){ intcmp=Double.compare(number,((Pair)o).number); if(cmp!=0){ returncmp; } returnname.compareTo(((Pair)o).name); } thrownewClassCastException("CannotcomparePairwith" +o.getClass().getName()); } publicStringtoString(){ returnname+''+number; } }
类似的C++代码:
typedefpair<string,int>PAIR; intcmp(constPAIR&x,constPAIR&y) { returnx.second>y.second; } map<string,int>m; vector<PAIR>vec; for(map<wstring,int>::iteratorcurr=m.begin();curr!=m.end();++curr) { vec.push_back(make_pair(curr->first,curr->second)); } sort(vec.begin(),vec.end(),cmp);
Encapsulatetheinformationinitsownclass.Eitherimplement
Comparableandwriterulesforthenaturalorderingorwritea
Comparatorbasedonyourcriteria.Storetheinformationinasorted
collection,orusetheCollections.sort()method.