【Java-30】统计字符串中单词个数(map、泛型、迭代器遍历综合应用)

package bao_1;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 统计一个字符串单词数目
 * map
 * 泛型
 * 迭代器遍历
 * @author 慧天地
 *
 */
public class Statistic_word {
	public static void main(String[] args) {

		String str = "Statistics suggest that the population of this country will be double in ten years' time this country will Statistics suggest that the population of this country will be double in ten years' time this country will";
		String string[] = str.split(" ");
		Map<String, Integer> map = new HashMap<String, Integer>();
		for (int i = 0; i < string.length; i++) {
//			System.out.println(string[i]);
			if (!map.containsKey(string[i])) {
				map.put(string[i], 1);
			} else {
				map.put(string[i], map.get(string[i]) + 1);
			}

		}
		
		Set<String> set=map.keySet();
		Iterator<String> iter=set.iterator();
		while(iter.hasNext()){
			
			String word=iter.next();
			int count=map.get(word);
			System.out.println(word+"---"+count);
			
			
		}

	}

}

猜你喜欢

转载自blog.csdn.net/weixin_42034217/article/details/86514570