java学习笔记之HashMap经典分拣存储

利用HashMap中key不能重复的特性。

案例一:

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

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

/**
 * 统计字符串中单词出现的次数
 * @author ly1
 *
 */
public class CountNumberOfWords {
    /**
     * 用HashMap进行分拣存储(1:N)
     * @param str
     */
    public static void run(String str){
        Map<String,Integer> map = new HashMap<>();

        String[] words = str.split(" ");
        //利用HashMap中key不能重复的特性进行分拣存储
        for(int i = 0; i < words.length; i++){
            if(map.containsKey(words[i])){
                map.put(words[i], map.get(words[i])+1);
            }else{
                map.put(words[i], 1);
            }
        }
        //将各个单词出现的次数打印出来
        for(String key : map.keySet()){
            System.out.println(key + "---------->" + map.get(key));
        }
    }

    public static void main(String[] args) {
        String str ="When summer comes, the air is stuffy and the"
        +"temperature is so high. Thanks to the invention of " +
        "air-condition, people are no longer suffer to the hot"+
        " weather, they can stay at the indoors and enjoy the"+
        " coolness that air-condition brings. But the problem"+
        " comes, when people count on air-condition for a long"+
        " time, their bodies will be weaker. Some people feel"+
        " dizzy and have no strength to do their work, some"+
        " people are easy to catch the cold. All of these"+
        " symptoms are typical illness which is from air condition."+
        " Though air-condition brings us comfort, we will get "+
        "sick if we use it all the time. We need to go outside often,"+
        " even is hot, what’s more, taking exercise is needed."+
        " The natural environment is suitable for us to live in,"+
        " we can’t count on air-condition for a long time.";
        CountNumberOfWords.run(str);
    }
}

案例二(面向对象+分拣存储):

定义一个Student类,属性:姓名:name;班级号:num;分数:score,现在将若干对象放入List中,统计每个班级的总分和平均分。

实现思路:将案例一种的Map<String,Integer>换为Map<Integer,ClassRoom>其中Integer表示班级号,ClassRoom表示班级类,里面有总分、学生数属性。这里就不实现了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值