HashMap分拣存储2:统计每个单词出现的次数(采用面向对象)

public class Sorting2 {
    /**
     * 1、分割字符串(按照空格来切割) 2、分拣存储 3、按要求查看 单词出现的次数 4、加入面向对象
     */
    public static void main(String[] args) {
        // 1、分割字符串(按照空格来切割)
        String str = "this is a cat and that is a mice and where is the food";
        String[] arr = str.split(" ");
        // 2、分拣存储
        Map map = new HashMap();
        for (String key : arr) {
            if (!map.containsKey(key)) {
                map.put(key, new Letter(key));
            }
            Letter value = map.get(key);
            value.setCount(value.getCount() + 1);

            //另一种存储方式
//          Letter value = map.get(key);
//          if (value == null) {
//              value = new Letter();
//              map.put(key, value);
//          }
//          value.setCount(value.getCount() + 1);
        }
        // 3、按要求查看 单词出现的次数
        for (String key : map.keySet()) {
            Letter value = map.get(key);
            System.out.println(key + "-->" + value.getCount());
        }
    }
}
public class Letter {
    private String name; // 单词
    private int count; // 次数
    public Letter() {
    }
    public Letter(String name) {
        this.name = name;
    }
    public Letter(String name, int count) {
        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;
    }
}

你可能感兴趣的:(【Java,基础】)