Map容器案例

案例讲解  --统计字符串出现的次数

package com.date;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class AccountStringDemo {
   public static void main(String[] args) {
     String[] strings= {"张三","谭磊","张三","李四","王五"};
     AccountUtil.printDate(AccountUtil.account(strings));
     
     
}
}

class AccountUtil{
    public static Map<String, Integer> account(String[] strings){
        Map<String, Integer> data=new HashMap<String, Integer>();
        for (int i = 0; i < strings.length; i++) {
            String string=strings[i];
            if(data.get(string)==null) {
                data.put(string, 1);
            }else {
                //取出key所对应的值加1
                data.put(string, data.get(string)+1);
                }
        }
        return data;
        
    }
    
    public  static void printDate(Map<String, Integer> data) {
        Set<Entry<String, Integer>> entries=data.entrySet();
        for (Entry<String, Integer> entry : entries) {
            System.out.println(entry.getKey()+"+++++"+entry.getValue());
        }
    }
}
原文地址:https://www.cnblogs.com/tanlei-sxs/p/9991322.html