【BigData】Java基础_HashMap

HashMap简介

HashMap是一种非常常见、方便和有用的集合,是一种键值对(K-V)形式的存储结构

常见的方法如下:

  • put:将数据添加到集合中
  • get:获取集合中的元素
  • size:获取集合的长度
  • remove:移除集合中的键值对
  • containsKey:判断指定的key是否存在

实战演练

1.HashMap的用法案例

package cn.test.logan.day06;

import java.util.HashMap;

public class HashMapDemo {
    public static void main(String[] args) {
        // 构建一个hashmap对象
        HashMap<String,String> map1 = new HashMap<>();
        
        // 添加元素
        map1.put("1", "Jack");
        map1.put("2", "Logan");
        map1.put("3", "Tom");
        map1.put("4", "Alice");
        
        // 获取元素
        String a = map1.get("2");
        System.out.println(a);
        
        // 获取长度
        int size = map1.size();
        System.out.println(size);
        
        // 从map1中移除元素
        String b = map1.remove("3");
        System.out.println(b);
        
        // 判断数据是否存在
        boolean c = map1.containsKey("3");
        System.out.println(c);
    }
}
HashMapDemo.java

 2.使用HashMap计算字符串中每个单词的数量

package cn.test.logan.day06;

import java.util.HashMap;
import java.util.Set;

public class HashMapWordCount {
    public static void main(String[] args) {
        String str = "a,c,v,b,s,d,a,b,s,f,s";
        String[] arr = str.split(",");
        
        HashMap<String,Integer> countMap = new HashMap<>();
        
        /**
         * 将数组中的元素依次装入到HashMap中,
         * 如果已经存在HashMap中,那么在数量字段上加1
         * 如果不存在,那么将字符存入,计数为1
         */
        for(String word:arr) {
            if(countMap.containsKey(word)) {
                Integer value = countMap.get(word);
                countMap.put(word, value+1);
            }else {
                countMap.put(word, 1);
            }
        }
        /**
         * 遍历HashMap,打印数据
         */
        // 先取出所有的key
        Set<String> keyset = countMap.keySet();
        // 根据key,取出value
        for(String key:keyset) {
            Integer count = countMap.get(key);
            System.out.println("字符"+key+",数量为:"+count);
        }
    }
}
HashMapWordCount.java
原文地址:https://www.cnblogs.com/OliverQin/p/12076649.html