java中map的应用

map是键值对的集合接口,需要存储两个字段有联系的字段时可以使用这个。

1、查找字符串数组重复次数最多的字符串的重复次数

思路:使用map键值对存储,key值存数字符串,value存储出现的次数    

Map map = new HashMap();

String [] ss = {"abc","123","123","456","abc","dgb","123"};

for(String s :ss)

{       Integer count = map.get(s);

        map.put(s, count == null?1:count+1);    }    //统计当前字符串出现的次数

        int max = 0;

        for(Map.Entry entry:map.entrySet())

            {     

                    if (entry.getValue()>max)

                    max = entry.getValue();

}

 2、给定String,求此字符串的单词数量。字符串不包括标点,大写字母。例如 String str="hello world hello city";单词数量为3,分别是:hello world city

public static void main(String [] args) {
int count = 0;
String str
="hello world hello city";
String newStr
="";
HashMap
<String,String> m=new HashMap<String,String>();
String [] a
=str.split(" "); //空格分隔字符串
for (int i=0;i<a.length;i++){
if(!m.containsKey(a[i])){ //判断Map集合对象中是否包含指定的键名。如果Map集合中包含指定的键名,则返回true,否则返回false
m.put(a[i],
"1");
count
++;
newStr
=newStr+" "+a[i]; } } System.out.println("这段短文单词的个数是:"+count+","+
newStr); }

 

posted @ 2017-11-24 11:18  爱吃橙子  阅读(645)  评论(0编辑  收藏  举报