Java 练习

用HashMap统计字符串中单词出现的次数。

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

public class Main {

    public static void main(String[] args) {
        String word = "hello tom\n" +
                "hello rose\n" +
                "hello jerry\n" +
                "hello TBL\n" +
                "hello tom\n" +
                "hello kitty\n" +
                "hello rose\n" +
                "hello TBL\n" +
                "hello ZDP\n" +
                "hello ZDP\n" +
                "hello TBL";
        //创建HashMap对象
        Map<String, Integer> map = new HashMap<String,Integer>();
        //将word以“\n”拆分
        String[] split = word.split("\n");
        //把拆分后的字符串数组循环取出
        for (String w:split) {
            //取出每个元素在意 空格拆分,返回的右是一个字符串数组
            String[] split1 = w.split(" ");
            //循环把split1里元素取出来
            for (int i = 0; i <split1.length ; i++) {
                //判断是否包含指定的键名
                if (map.containsKey(split1[i])){
                    Integer integer = map.get(split1[i]);
                    integer++;
                    map.put(split1[i],integer);
                }
                if (!map.containsKey(split1[i])){
                    map.put(split1[i],1);
                }

            }
        }
        for (Map.Entry<String,Integer> m:map.entrySet()) {
            System.out.println(m.getKey() + " : " + m.getValue() );
        }
        System.out.println("---------------------");
        //第二种
        for (String key:map.keySet()) {
            System.out.println("key= " + key);
        }
        for (Integer value:map.values()) {
            System.out.println("value= " + value);
        }
        System.out.println("-------------------");
        //第三种
        for (String key1 : map.keySet()) {
            Integer value1 = map.get(key1);
            System.out.println(key1 + " : " + value1);

        }

    }
}

结果

tom : 2
ZDP : 2
rose : 2
hello : 11
jerry : 1
kitty : 1
TBL : 3
---------------------
key= tom
key= ZDP
key= rose
key= hello
key= jerry
key= kitty
key= TBL
value= 2
value= 2
value= 2
value= 11
value= 1
value= 1
value= 3
-------------------
tom : 2
ZDP : 2
rose : 2
hello : 11
jerry : 1
kitty : 1
TBL : 3
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值