码迷,mamicode.com
首页 > 其他好文 > 详细

"分拣" 思路 统计每个单词出现的次数

时间:2014-09-29 01:37:06      阅读:314      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   使用   ar   java   for   sp   

package collection.map;

public class Letter {
	public String name;
	public int count;
	
}

  

package collection.map;
/*
 * 统计每个单词出现的次数
 * "分拣" 思路
 * 1、为所有key创建容器
 *    之后容器中存放对应value
 * 2、第一次创建容器,并存放值value
 *    第二次之后,直接使用容器存放值
 */
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MapDemo01 {

    private static void test1(String str)
    {
        String[] strArr = str.split(" ");        //分割字符串
        Map<String,Letter> letterMap = new HashMap<String, Letter>();
        for(String key : strArr)
        {
            Letter col = null;
            if(null == (col = letterMap.get(key)))
            {
                col = new Letter();
                col.count = 1;
                letterMap.put(key, col);
            }
            else
            {
                col.count++;
            }
        }
        
        Set<String> keys = letterMap.keySet();
        for(String key:keys)
        {
            Letter col = letterMap.get(key);
            System.out.println("单词:"+key+", 次数: "+col.count);
        }
    }
    
    private static void test2(String str)
    {
        String[] strArr = str.split(" ");
        Map<String,Integer> letterMap = new HashMap<String,Integer>();
        for(String temp : strArr)
        {
            int count = 0;
            if(letterMap.containsKey(temp))
            {
                count = letterMap.get(temp);
            }
            letterMap.put(temp, ++count);
        }
        
        //输出Map的值
        Set<String> keys = letterMap.keySet();
        for(String key:keys)
        {
            System.out.println("单词:"+key+",次数:"+letterMap.get(key));
        }
    }
    
    public static void main(String[] args) {
        String str = "you know new york , you need new york . you know you need unique new york .";
        
        test1(str);
        System.out.println("-----------");
        test2(str);
        
    }
    

}

 

"分拣" 思路 统计每个单词出现的次数

标签:style   blog   color   io   使用   ar   java   for   sp   

原文地址:http://www.cnblogs.com/fancyzhen/p/3999275.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!