Java之统计字符串中字符个数

 统计字符串中每个字符出现的次数,在控制台按降序进行打印输出 如:a:100 b:80 c:50

public class TestPractise {
	/*
	 * 统计字符串中每个字符出现的次数,在控制台按降序进行打印输出 如:a:100 b:80 c:50
	 */
	@Test
	public void test() {
		String str = "dasdsadsadasdasd";
		
		Map<Character, Integer> map=new HashMap<Character, Integer>();
		for (int i = 0; i < str.length(); i++) {
			Set<Character> keyset = map.keySet();
			boolean flag=false;
			Character key = str.charAt(i);
			Integer count=1;
			for (Character key1 : keyset) {
				if(key1==str.charAt(i)) {
					key=key1;
					count=map.get(key)+1;
					flag=true;
					break;
				}
			}
			if(flag) {
				map.remove(key);
			}
			map.put(key, count);
			
		}
		
		Set<Character> keyset1 = map.keySet();
		for (Character key : keyset1) {
			System.out.println(key+"\t"+map.get(key));
		}
		
		List<Entry<Character,Integer>> list=new ArrayList<Entry<Character,Integer>>(map.entrySet());
		Collections.sort(list, new Comparator<Map.Entry<Character,Integer>>() {
			@Override
			public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
				// TODO Auto-generated method stub
				if(o1.getValue()>o2.getValue()) {
					return -1;
				}
				return 1;
			}
		});
		System.out.println("排序后:");
		for(Entry<Character,Integer> x:list) {
			System.out.println(x.getKey()+"\t"+x.getValue());
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_34361514/article/details/81607718