Map集合方法及常用实现类

1.1Map集合概述和特点

Map接口概述
查看API可以知道:
将键映射到值的对象
一个映射不能包含重复的键
每个键最多只能映射到一个值
map接口和Collection接口的区别:

  Map接口和Collection接口的不同
  Map是双列的,Collection是单列的
  Map的键唯一,Collection的子体系Set是唯一的
   Map集合的数据结构针对键有效,跟值无关;Collection集合的数据结构是针对元素有效

1.2功能概述

a:添加功能 
	V put(K key,V value):添加元素。这个其实还有另一个功能?替换
		如果键是第一次存储,就直接存储元素,返回null
		如果键不是第一次存在,就用值把以前的值替换掉,返回以前的值
b:删除功能
	void clear():移除所有的键值对元素
	V remove(Object key):根据键删除键值对元素,并把值返回
c:判断功能
	boolean containsKey(Object key):判断集合是否包含指定的键
	boolean containsValue(Object value):判断集合是否包含指定的值
	boolean isEmpty():判断集合是否为空
d:获取功能
	Set<Map.Entry<K,V>> entrySet(): 返回一个键值对的Set集合
	V get(Object key):根据键获取值
	Set<K> keySet():获取集合中所有键的集合
	Collection<V> values():获取集合中所有值的集合
e:长度功能
	int size():返回集合中的键值对的对数

Map集合的遍历之键找值

    public static void main(String[] args) {
        HashMap<String, Integer> hashMap = new HashMap<>();
        hashMap.put("abc",100);
        hashMap.put(null,200);
        hashMap.put("bbb",null);
        hashMap.put(null,null);

        System.out.println(hashMap);
        Set<String> keySet = hashMap.keySet();
        for (String key : keySet) {
            System.out.println(key+"=="+hashMap.get(key));

Map集合的遍历之键值对对象找键和值

public class My2BianLi {
    public static void main(String[] args) {
        HashMap<String, Integer> hashMap = new HashMap<>();
       	 	hashMap.put("abc",100);
        	hashMap.put(null,200);
       		 hashMap.put("bbb",null);
        	hashMap.put(null,null);
        
		Set<Map.Entry<String, Integer>> entries = hashMap.entrySet();
        for (Map.Entry<String, Integer> entry : entries) {
            String key = entry.getKey();
            Integer value = entry.getValue();
            System.out.println(key+"==="+value);
        }

1.3 HashMap集合键是Stirng值是String的案例

案例演示:
允许插入null键 null值

public class My2BianLi {
    public static void main(String[] args) {
        HashMap<String, Integer> hashMap = new HashMap<>();
       	 	hashMap.put("abc",100);
        	hashMap.put(null,200);
       		 hashMap.put("bbb",null);
        	hashMap.put(null,null);
        
		Set<Map.Entry<String, Integer>> entries = hashMap.entrySet();
        for (Map.Entry<String, Integer> entry : entries) {
            String key = entry.getKey();
            Integer value = entry.getValue();
            System.out.println(key+"==="+value);
        }

2.1LinkedHashMap的概述和使用

LinkedHashMap的概述: Map 接口的哈希表和链接列表实现,具有可预知的迭代顺序
B:LinkedHashMap的特点: 底层的数据结构是链表和哈希表 元素有序 并且唯一
元素的有序性由链表数据结构保证 唯一性由 哈希表数据结构保证
Map集合的数据结构只和键有关

3.1TreeMap集合键是String值是String的案例

注意:TreeMap 键不允许插入null
//由于是二叉树底层数据结构,在主方法上要实现一个Compator接口****或者在类中实现Compable接口,且重写ComperTo接口。
TreeMap: 键的数据结构是红黑树,可保证键的排序和唯一性
排序分为自然排序和比较器排序
线程是不安全的效率比较高

public class MyTest {
    public static void main(String[] args) {

        TreeMap<Student, Integer> treeMap = new TreeMap<>(new Comparator<Student>() {
            @Override
            public int compare(Student S1, Student S2) {
                int num=S1.getAge()-S2.getAge();
                int num2=num==0?S1.getName().compareTo(S2.getName()):num;
                return num2;
            }
        });
        treeMap.put(new Student("李卓炅",1),1);
        treeMap.put(new Student("简盈凡", 10), 1);
        treeMap.put(new Student("许显军", 12), 1);
        treeMap.put(new Student("小飞飞", 122), 1);
        treeMap.put(new Student("张三", 144), 1);
        treeMap.put(new Student("李四", 109), 1);
        treeMap.put(new Student("王五", 156), 1);
        treeMap.put(new Student("赵六", 124), 1);
        treeMap.put(new Student("狗东西", 124), 1);
        //用比较器排序
        Set<Map.Entry<Student, Integer>> entries = treeMap.entrySet();
        for (Map.Entry<Student, Integer> entry : entries) {
            Student key = entry.getKey();
            Integer value = entry.getValue();
            System.out.println(key.getName()+"----"+key.getAge()+"----"+value);
        }

    }
}

3.2统计字符串中每个字符出现的次数

案例演示:

public class MyZiFuChuan {
    public static void main(String[] args) {
        //1、统计一个字符串中每个字符出现的次数
        Scanner scanner = new Scanner(System.in);
        System.out.println("请随便输入一行字符");
        String line = scanner.nextLine();
        HashMap<Character, Integer> hashMap = new HashMap<>();
        for (int i = 0; i < line.length(); i++) {
            //截取字符,作为键,存到集合中
            char ch = line.charAt(i);
            if(!hashMap.containsKey(ch)){
                hashMap.put(ch,1);
            }else{
                Integer integer = hashMap.get(ch);
                integer++;
                hashMap.put(ch,integer); //键相同,值覆盖
            }
        }

        //当这些数据存进去后,遍历集合,拼串拼成我想要的形状
        StringBuilder sb = new StringBuilder();
        Set<Character> keySet = hashMap.keySet();
        for (Character key : keySet) {
            sb.append(key).append("(").append(hashMap.get(key)).append(")");
        }
        String s = sb.toString();
        System.out.println(s);

3.3集合嵌套之HashMap嵌套HashMap

案例演示:
基础班
张三 20
李四 22
就业班
王五 21
赵六 23

public class MTest {
    public static void main(String[] args) {
        /* HashMap嵌套HashMap
           HashMap嵌套ArrayList*/
        HashMap<String, Integer> jcMap = new HashMap<>();
        jcMap.put("张三",20);
        jcMap.put("李四",22);

        HashMap<String, Integer> jyMap = new HashMap<>();
        jyMap.put("王五", 21);
        jyMap.put("赵六", 23);

        HashMap<String, HashMap<String, Integer>> minMap = new HashMap<>();
        minMap.put("基础班",jcMap);
        minMap.put("就业班",jyMap);
        //遍历集合
        //遍历集合
        Set<Map.Entry<String, HashMap<String, Integer>>> entries = minMap.entrySet();
        for (Map.Entry<String, HashMap<String, Integer>> en : entries) {
            String key = en.getKey();
            System.out.println(key);
            HashMap<String, Integer> value = en.getValue();
            Set<Map.Entry<String, Integer>> entries1 = value.entrySet();
            for (Map.Entry<String, Integer> entry : entries1) {
                String key1 = entry.getKey();
                Integer value1 = entry.getValue();
                System.out.println("\t"+key1+"\t"+value1);
            }
            System.out.println();
        }

    }
}

3.4ArrayList嵌套HashMap

案例演示:
三国演义
吕布
周瑜
笑傲江湖
令狐冲
林平之
神雕侠侣
郭靖
杨过
* */

public class MyTest2 {
    public static void main(String[] args) {

       //HashMap 嵌套 ArrayList
        ArrayList<String> sgList = new ArrayList<>();
        sgList.add("吕布");
        sgList.add("周瑜");

        ArrayList<String> xaList = new ArrayList<>();
        xaList.add("令狐冲");
        xaList.add("林平之");

        ArrayList<String> sdList = new ArrayList<>();
        sdList.add("郭靖");
        sdList.add("杨过");

        HashMap<String, ArrayList<String>> listHashMap = new HashMap<>();
        listHashMap.put("三国演义",sgList);
        listHashMap.put("笑傲江湖", xaList);
        listHashMap.put("神雕侠侣", sdList);
        //遍历集合
        Set<Map.Entry<String, ArrayList<String>>> entries = listHashMap.entrySet();
        for (Map.Entry<String, ArrayList<String>> entry : entries) {
            String key = entry.getKey();
            System.out.println(key);
            ArrayList<String> value = entry.getValue();
            for (String s : value) {
                System.out.println("\t"+s);
            }
            System.out.println();

        }
        
    }
}

3.4.1HashMap和Hashtable的区别

A:Collections类概述: 针对集合操作 的工具类
B:Collections成员方法
public static void sort(List list): 排序,默认按照自然顺序
public static int binarySearch(List<?> list,T key): 二分查找
public static T max(Collection<?> coll): 获取最大值
public static void reverse(List<?> list): 反转
public static void shuffle(List<?> list): 随机置换

模拟斗地主洗牌和发牌

演示案例:

public class MyDemo {
    public static void main(String[] args) {
        HashMap<Integer, String> pokerBox = new HashMap<>();
        //定义花色
        String[] colors = {"♣", "♠", "♥", "◆"};
        // 定义牌号数组
        String[] nums = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10","J", "Q", "K"};
        //定义一个索引集合
        ArrayList<Integer> indexs = new ArrayList<>();
        int index=0;
        for (String num : nums) {
            for (String color : colors) {
                pokerBox.put(index,num.concat(color));
                indexs.add(index);
                index++;
            }
        }
        //手动添加大小王
        pokerBox.put(index,"?");
        indexs.add(index);
        index++;
        pokerBox.put(index,"☀");
        indexs.add(index);


        // //洗牌,洗索引集合
        Collections.shuffle(indexs);
        //System.out.println(indexs);
        // System.out.println(pokerBox);
        // //发牌
        TreeSet<Integer> 许显军 = new TreeSet<>();
        TreeSet<Integer> 李卓炅 = new TreeSet<>();
        TreeSet<Integer> 简盈凡 = new TreeSet<>();
        TreeSet<Integer> 底牌 = new TreeSet<>();
        //发牌发的是索引
        for (int i = 0; i < indexs.size(); i++) {
            if (i >= indexs.size() - 3) {
                // 留底牌
                底牌.add(indexs.get(i));
            }else
            if (i % 3 == 0) {
                许显军.add(indexs.get(i));

            } else if (i % 3 == 1) {
                李卓炅.add(indexs.get(i));

            } else if (i % 3 == 2) {
               简盈凡 .add(indexs.get(i));
            }

        }

        //看牌
        lookPoker("许显军",许显军,pokerBox);
        lookPoker("李卓炅", 李卓炅, pokerBox);
        lookPoker("简盈凡", 简盈凡, pokerBox);
        lookPoker("底牌", 底牌, pokerBox);

    }

    private static void lookPoker(String name, TreeSet<Integer> set, HashMap<Integer, String> pokerBox) {
        System.out.println(name);
        for (Integer key : set) {
            System.out.print(pokerBox.get(key)+"  ");
        }
        System.out.println();


    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值