Java 中Map的使用,以及遍历

 

https://poj.org/problem?id=1002

 

/*
 * 1. 用TreeMap<String,Integer>;
 * 2. 接收字符串,逐个判断,数字直接相加,字符转换成数字,‘-’不管,组成的字符串放到Map
 * 3. 输出Map中value>1的项
 * 
 * */

import java.util.*;

public class Main {
	public static void main(String[] args) {
		//jdk1.6以下的不能这样定义 TreeMap <String,Integer> map = new TreeMap<>();
		TreeMap <String,Integer> map = new TreeMap<String,Integer>();  
		Scanner cin = new Scanner(System.in);
		int t = cin.nextInt();
		String s,str;
		char ch;
		int i;
		while(t--!=0){
			s = cin.next();
			str = "";
			for(i=0;i<s.length();i++){
				ch = s.charAt(i);
				if(ch>='0' && ch<='9') str += ch+"";
				else if(ch=='-') continue;
				else{
					switch (ch) {
						case 'A':case 'B':case 'C':  str += "2"; break;
						case 'D':case 'E':case 'F':  str += "3"; break;
						case 'G':case 'H':case 'I':  str += "4"; break;
						case 'J':case 'K':case 'L':  str += "5"; break;
						case 'M':case 'N':case 'O':  str += "6"; break;
						case 'P':case 'R':case 'S':  str += "7"; break;
						case 'T':case 'U':case 'V':  str += "8"; break;
						case 'W':case 'X':case 'Y':  str += "9"; break;
					}
				}
				if(str.length() == 3) str += "-";
			}
			int cnt;
			if(map.containsKey(str))  {
				cnt = map.get(str)+1;
				map.remove(str);
				map.put(str, cnt);
			}else{
				map.put(str, 1);
			}
		}
		Iterator<String> it = map.keySet().iterator();
		String key;int num;
		int flag = 0;
		while(it.hasNext()){
			key = it.next();
			num = map.get(key);
			if( num>1 ){
				flag = 1;System.out.println(key+" "+ num);
			}
		}
		if(flag==0)System.out.println("No duplicates.");
	}
}