HaspMap分拣思路

package Map01;

public class Letter {
    private String name;
    private int count;
    
    public Letter(){
        
    }
    
    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;
    }
    
    
}
package Map01;

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

public class test {

    public static void main(String[] args) {
        
        String str = "this is a cat and that is a mice and where is food";
        String[] strArray = str.split(" ");
        Map<String, Letter> letters = new HashMap<String, Letter>();
        
        for (String temp: strArray){
            Letter col = null;
            if(null == (col = letters.get(temp))){
                col = new Letter();
                col.setCount(1);
                letters.put(temp, col);
            }else{
                col.setCount(col.getCount() + 1);
            }
            
        }
        
        Set<String> keys = letters.keySet();
        for (String key: keys){
            Letter col = letters.get(key);
            System.out.println("字母:" + key + ",次数" + col.getCount());
        }
    }

}

运行结果:

字母:a,次数2
字母:that,次数1
字母:and,次数2
字母:cat,次数1
字母:this,次数1
字母:is,次数3
字母:where,次数1
字母:mice,次数1
字母:food,次数1

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。