一.HashMap的应用思路

  使用: Map,Set集合,String的split切割方法 ,增强for循环

   使用思路:为所有key创建容器,之后容器中存放对应value

二.实现示例代码

  1.两个类,Letter类,类似于javaBean类型,Demo02测试类

  2.Letter类  

    

package com.ahd.map;

public class Letter {
private String name;
private int count=1; public Letter() {
super();
} public Letter(String name, int count) {
super();
this.name = name;
this.count = count;
} public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
} }

Letter

  3.Demo01类

    

package com.ahd.map;

import java.util.HashMap;
import java.util.Map;
import java.util.Set; //HashMap的思路
public class Demo02 {
public static void main(String[] args) {
//创建HashMap
Map<String,Letter> map=new HashMap<String,Letter>(); //创建测试的字符串
String str="this is my way but i fucking love you that is our dream";
//切割字符串,转成字符串数组
String []strArray=str.split(" "); //进行增强for循环,创建hashmap中key值
for(String temp:strArray){ if(!map.containsKey(temp)){
map.put(temp, new Letter());
} //计数设置
Letter col=map.get(temp);
col.setCount(col.getCount()+1);
} //进行遍历 通过set集合来封装key
Set<String> set=map.keySet();
for(String key:set){
System.out.println("key:"+key);
System.out.println("value(count):"+map.get(key).getCount());
}
} }

Demo02

05-06 15:48