zoukankan      html  css  js  c++  java
  • 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); }
  • 相关阅读:
    P3383 【模板】线性筛素数
    POJ2431-Expedition【优先队列+贪心】
    HDU1087
    HDU1029
    最小生成树之Kruskal算法
    AC自动机模板
    328闯关解析
    php可获取客户端信息
    $( ).focus()与$( )[0].focus()区别
    RegExp类型和text()方法
  • 原文地址:https://www.cnblogs.com/fulucky/p/7889691.html
Copyright © 2011-2022 走看看