基于Key-Value对的排序(Java版)

来源:互联网 发布:杨过 郭芙 知乎 编辑:程序博客网 时间:2024/05/16 12:35

最近在带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());    }    }           }


0 0
原创粉丝点击