Java基础17--Map(三)

2014-11-24 03:32:05 · 作者: · 浏览: 2
存在,就将该字母键对应值取出并+1,再将该字母+1后的值存储到Map集合中。

(3)遍历结束,map集合就记录所有的字母出现的次数。

public class MapTest {
	public static void main(String[] args) {
		String str = "fdg+avAdc  bs50da9c-fds";
		String s = getCharCount(str);
		System.out.println(s);
	}
	public static String getCharCount(String str) {
		char[] chs = str.toCharArray();
		Map
  
    map = new TreeMap
   
    (); for(int i = 0 ; i < chs.length ; i++) { if(!(chs[i]>='a'&&chs[i]<='z'||chs[i]>='A'&&chs[i]<='Z')) continue; Integer value = map.get(chs[i]); int count = 1; if(value != null) count = value + 1; map.put(chs[i],count); } return mapToString(map); } private static String mapToString(Map
    
      map) { StringBuilder sb = new StringBuilder(); Iterator
     
       it = map.keySet().iterator(); while(it.hasNext()) { Charactor key = it.next(); Integer value = map.get(key); sb.append(key+"("+value+")"); } return sb.toString(); } } 
     
    
   
  

17-11,Map查表法练习

1,Map在有映射关系时可以优先考虑,在查表法中的应用较为多见。

2,若要查一班的张三,一班的李四怎么办?

map.put("一班","张三");

map.put("一班","李四");

这是不行的,键相同,李四会把张三覆盖。

可以在值得位置上加一个集合,如:map.put("一班",Set );这样一班就对应一个集合了。

3,查表法练习-星期

public class MapTest {
	public static void main(String[] args) {
		String week = getWeek(1);
		System.out.println(week);
		System.out.println(getWeekByMap(week));
	}
	public static String getWeekByMap(String week) {
		Map
  
    map = new HashMap
   
    (); map.put("星期一","Mon"); map.put("星期二","Tus"); map.put("星期三","Wed"); map.put("星期四","Thu"); map.put("星期五","Fri"); map.put("星期六","Sat"); map.put("星期日","Sun"); map.put("星期天","Sun"); return map.get(week); } public static String getWeek(int week) { if(week < 1 || week > 7) { throw new RuntimeException("没有对应的星期"); } String[] weeks = {"","星期一","星期二","星期三","星期四","星期五","星期六","星期日"}; return weeks[week]; } }