使用以下代碼創建一個hashmap,然後使用樹形圖和比較器對hashmap中的值進行排序。但是,輸出是相當意想不到的。 因此,任何想法,以什麼林做錯了會很有幫助使用TreeMap和比較器按值排序HashMap
代碼
public static void main(String[] args) {
System.out.println("Most freq"+mostFreq(" i me hello hello hello me"));
}
public static String[] mostFreq(String str){
if ((str==null)||(str.trim().equalsIgnoreCase("")))
return null;
String[] arr = new String[10];
String[] words= str.split(" ");
Map <String,Integer> map = new HashMap<String,Integer>();
for (String word :words)
{
int count =0;
if (map.containsKey(word))
{
count= map.get(word);
map.put(word, count+1);
}
else
map.put(word, 1);
}
MyComparator comp= new MyComparator(map);
Map<String,Integer> newMap= new TreeMap(comp);
newMap.putAll(map);
Iterator it= newMap.entrySet().iterator();
while (it.hasNext())
{
Map.Entry pairs = (Map.Entry) it.next();
System.out.println("Key "+pairs.getKey()+"-- value"+pairs.getValue());
}
return arr;
}
這裏是比較
package samplecodes;
import java.util.Comparator;
import java.util.Map;
public class MyComparator implements Comparator {
Map map;
public MyComparator(Map map){
this.map=map;
}
@Override
public int compare(Object o1, Object o2) {
return ((Integer)map.get(o1) >(Integer)map.get(o2)? (Integer)map.get(o1):(Integer)map.get(o2));
}
}
和輸出的形式
me-2
hello-3
i-3
您的代碼不會生成此輸出。你確定這是你正在使用的? – Pshemo
也可以看看[在Java中如何對數據進行排序,然後進行排序](http://stackoverflow.com/questions/109383/how-to-sort-a -code-value-on-the-values-in-java) – Pshemo
你的代碼中有很多難聞的氣味:請爲你的Map,Iterator等添加泛型類型參數。在'mostFreq()'你正在返回'arr'只是一個空字符串數組,在方法中從未被觸及過。我也在回答關於你的邏輯問題的回答 –