문자열 정렬 및 통계

통계 문자열 '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();
	}

}

좋은 웹페이지 즐겨찾기