统计字符串”abadcdffbaeba”中每个字符出现了多少次,按次数排序并输出。例如:c : 1,e : 1,d : 2,f : 2,b : 3,a : 4
package com.heima.question7;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
public class StringStatictis {
@Test
public void test(){
String originalString = "abadcdffbaeba";
String resultString = stringStatictis(originalString);
String expectedString = "c:1,e:1,d:2,f:2,b:3,a:4";
assertEquals(expectedString,resultString);
}
public static void main(String[] args){
String originalString = "abadcdffbaeba";
String resultString = stringStatictis(originalString);
String expectedString = "c:1,e:1,d:2,f:2,b:3,a:4";
System.out.println(resultString);
}
@SuppressWarnings("unchecked")
public static String stringStatictis(String originalString){
char[] charArray = originalString.toCharArray();
List<Character> list = new ArrayList<Character>();
for(char c : charArray){
list.add(c);
}
/**
* 将统计结果存在一个Map当中,key为出现的字符,value为字符出现的次数
*/
Map<Character,Integer> map = new HashMap<Character,Integer>();
/**
* 取得并移除list中的第一个元素,将其作为key并将其与list中的其它key相比较,如果相等,则将其元素同样从list中移除,
* 同时,将key所对应的value值加1
*/
while(list.size()>0){
char key = list.remove(0);
Integer value = 1 ;
int newListSize = list.size();
int j=0;
for(int i=0;i<newListSize;i++){
if(key==list.get(j)){
list.remove(j);
value++;
}else{
j++;
}
}
map.put(key, value);
}
List sortList = new ArrayList(map.entrySet());
/**
* 对sortList中的元素进行排序:
* 1.按字符出现的次数排序,出现次数多的排在后面
* 2.如果字符次数相等,则将小字符排在前面
*/
Collections.sort(sortList,new Comparator(){
@Override
public int compare(Object o1, Object o2) {
Map.Entry obj1 = (Map.Entry) o1;
Map.Entry obj2 = (Map.Entry) o2;
if((Integer)obj1.getValue()==(Integer)obj2.getValue()){
return (Character)obj1.getKey() - (Character)obj2.getKey();
}else{
return (Integer)obj1.getValue()-(Integer)obj2.getValue();
}
}
});
StringBuilder sb = new StringBuilder();
for(Object obj:sortList){
Map.Entry entry = (Map.Entry)obj;
sb.append(entry.getKey()+":"+entry.getValue()+",");
}
sb.deleteCharAt(sb.length()-1);
return sb.toString();
}
}