基於Key-Value對的排序(Java版)

最近在帶Java的助教,有個實驗題要求:

編程接受用戶輸入的一段英文文字,使用一個數組統計每個字母(不計大小寫)出現的次數相對於字母總數的比率,打印顯示這個比率。並對字母出現的比率進行排序。

我第一反映是存在一個Map裏面進行排序,但是hashmap貌似沒有sort方法,需要轉成List.

import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.text.*;
import java.math.*;
import java.util.regex.*;



public class Solution {
	

    public static void main(String[] args) {
    	
 
    	HashMap<String,Double> hm = new HashMap<String,Double>();
    	 hm.put("a", 6.0);
    	 hm.put("d",5.0);
    	 hm.put("b",5.0);
    	 hm.put("e",5.0);
    	
    	 
    	/* Iterator it = hm.entrySet().iterator();
    	 while(it.hasNext())
    	 {
    		 Map.Entry entry = (Map.Entry)it.next();
              System.out.println("next : "+ entry.getKey() +" - "+entry.getValue());
    	 }*/
    	 //List<Map.Entry<Integer,Integer>> list=new ArrayList<Map.Entry<Integer,Integer>>(); 
    	 List<Map.Entry<String,Double>> list=new ArrayList<>();  
    	 list.addAll(hm.entrySet());
    	 Collections.sort(list, new Comparator<Map.Entry<String, Double>>() {
    		 public int compare(Map.Entry<String, Double> o1,Map.Entry<String, Double> o2){
    			 if(o1.getValue().compareTo(o2.getValue())==0)
    				 return (o1.getKey().compareTo(o2.getKey()));
    				 else
    				return (o1.getValue().compareTo(o2.getValue()));
    			 
    		 }
		});
    	 
    	for (Entry<String, Double> entry : list) {
			System.out.println(entry.getKey()+" "+entry.getValue());
    	
		}
    	}
    
    	
   
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章