HashMap分拣存储1:统计每个单词出现的次数

    xiaoxiao2021-12-14  17

    public class Sorting { /** * 统计每个单词出现的次数 this is a cat and that is a mice and where is the food? * HashMap分拣存储 思想:实现1:N 一对多(一个键多个值) 分组:一个键一个容器 * * 1、分割字符串(按照空格来切割) 2、分拣存储 3、按要求查看 单词出现的次数 */ 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, Integer> map = new HashMap<String, Integer>(); for (String key : arr) { // 查看是否存在该单词 if (!map.containsKey(key)) { // 不存在 map.put(key, 1); } else { map.put(key, map.get(key) + 1); } //另一种存储方式 // Integer value = map.get(key); // if(value == null){ // map.put(key, 1); // }else{ // map.put(key, value + 1); // } } // 3、按要求查看 单词出现的次数 Set<String> keySet = map.keySet(); // 获取对象 Iterator<String> it = keySet.iterator(); while (it.hasNext()) { String key = it.next(); Integer value = map.get(key); System.out.println(key + "-->" + value); } } }
    转载请注明原文地址: https://ju.6miu.com/read-965411.html

    最新回复(0)