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

    xiaoxiao2021-12-14  17

    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<String, Letter> map = new HashMap<String, Letter>(); 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; } }
    转载请注明原文地址: https://ju.6miu.com/read-965534.html

    最新回复(0)