統計字符串中每個字符重復出現的次數,並按照從大到小或從小到大順序輸出


public static void test(String str){

Map<String,Integer> map = new HashMap<>();

for(int i = 0 ;i < str.length();i++){

String s = str.charAt(i) + "";
if(map.containsKey(s)){
int value = map.get(s);
map.put(s,value + 1);
}else{

map.put(s,1);

}
}

List<Map.Entry<String,Integer>> list = new ArrayList<>(map.entrySet());

Collections.sort(list,new Comparator<Map.Entry<String,Integer>>(){
@Override
public int compare(Map.Entry<String,Integer> o1,Map.Entry<String,Integer> o2){
            //從小到大排序
return o1.getValue() - o2.getValue();
            //從大到小排序
            return o2.getValue() - o1.getValue();

}

}


);

for(Map.Entry<String,Integer> m: list){

System.out.println(m.getKey() + "---" + m.getValue());

}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM