Java中的Map及其使用「建议收藏」

Java中的Map及其使用「建议收藏」MapMap集合概述和特点概述:将键映射到值的对象一个映射不能包含重复的键每个键最多只能映射到一个值Map接口和Collection接口的不同Map是双列的,Collection是单列的Map的键唯一,Collection的子体系Set是唯一的Map集合的数据结构针对键有效,跟值无关;Collection集合的数据结构是针对元素有效Map集合的功能概述a:添加功能Vput…

大家好,又见面了,我是你们的朋友全栈君。

Map

Map集合概述和特点

概述:
将键映射到值的对象
一个映射不能包含重复的键
每个键最多只能映射到一个值
Map接口和Collection接口的不同
Map是双列的,Collection是单列的
Map的键唯一,Collection的子体系Set是唯一的
Map集合的数据结构针对键有效,跟值无关;Collection集合的数据结构是针对元素有效

Map集合的功能概述

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 keySet():获取集合中所有键的集合
Collection values():获取集合中所有值的集合
e:长度功能
int size():返回集合中的键值对的对数

Map集合的遍历之键找值

获取所有键的集合
遍历键的集合,获取到每一个键
根据键找值

public class Test4 {
    public static void main(String[] args) {
        HashMap<Phone,String> map = new HashMap<>();
        map.put(new Phone("Apple",7000),"美国");
        map.put(new Phone("Sony",5000),"日本");
        map.put(new Phone("Huawei",6000),"中国");
        Set<Phone> phones = map.keySet();
        Iterator<Phone> iterator = phones.iterator();
        while (iterator.hasNext()){
            Phone next = iterator.next();
            System.out.println(next.getBrand()+"=="+next.getPrice()+"=="+map.get(next));
        }

    }
}
class Phone{
    private String Brand;
    private int Price;

    public Phone(String brand, int price) {
        Brand = brand;
        Price = price;
    }

    public String getBrand() {
        return Brand;
    }

    public void setBrand(String brand) {
        Brand = brand;
    }

    public int getPrice() {
        return Price;
    }

    public void setPrice(int price) {
        Price = price;
    }
}

获取所有键值对对象的集合
遍历键值对对象的集合,获取到每一个键值对对象
根据键值对对象找键和值

public class Test4 {
    public static void main(String[] args) {
        HashMap<Phone,String> map = new HashMap<>();
        map.put(new Phone("Apple",7000),"美国");
        map.put(new Phone("Sony",5000),"日本");
        map.put(new Phone("Huawei",6000),"中国");
        Set<Map.Entry<Phone, String>> entries = map.entrySet();
        for (Map.Entry<Phone, String> entry : entries) {
            System.out.println(entry.getKey().getBrand()+"==="+entry.getKey().getPrice()+"==="+entry.getValue());
        }
    }
}

一般来说建议使用entrySet遍历方式,其效率高

LinkedHashMap的概述和使用

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

TreeMap集合

TreeMap 键不允许插入null
TreeMap: 键的数据结构是红黑树,可保证键的排序和唯一性
排序分为自然排序和比较器排序
线程是不安全的效率比较高
TreeMap集合排序:
实现Comparable接口,重写CompareTo方法
使用比较器

TreeMap集合的遍历

public class Test4 {
    public static void main(String[] args) {
        TreeMap<Phone,String> map = new TreeMap<>();
        map.put(new Phone("Apple",7000),"美国");
        map.put(new Phone("Sony",5000),"日本");
        map.put(new Phone("Huawei",6000),"中国");
        Set<Phone> phones = map.keySet();
        Iterator<Phone> iterator = phones.iterator();
        while(iterator.hasNext()){
            Phone next = iterator.next();
            System.out.println(next.getBrand()+"==="+next.getPrice()+"==="+map.get(next));
        }
    }
}
class Phone implements Comparable<Phone>{
    private String Brand;
    private int Price;

    public Phone(String brand, int price) {
        Brand = brand;
        Price = price;
    }

    public String getBrand() {
        return Brand;
    }

    public void setBrand(String brand) {
        Brand = brand;
    }

    public int getPrice() {
        return Price;
    }

    public void setPrice(int price) {
        Price = price;
    }

    @Override
    public int compareTo(Phone o) {
        return this.getPrice() - o.getPrice();
    }
}

集合嵌套之HashMap嵌套HashMap

基础班
张三 20
李四 22
就业班
王五 21
赵六 23

public class Test5 {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("张三",20);
        map.put("李四",22);
        HashMap<String, Integer> map1 = new HashMap<>();
        map1.put("王五",21);
        map1.put("赵六",23);
        HashMap<String, HashMap<String, Integer>> mapmax = new HashMap<>();
        mapmax.put("基础班",map);
        mapmax.put("就业班",map1);
        Set<Map.Entry<String, HashMap<String, Integer>>> entries = mapmax.entrySet();
        for (Map.Entry<String, HashMap<String, Integer>> entry : entries) {
            System.out.println(entry.getKey());
            Set<Map.Entry<String, Integer>> entries1 = entry.getValue().entrySet();
            for (Map.Entry<String, Integer> stringIntegerEntry : entries1) {
                System.out.println("\t"+stringIntegerEntry.getKey()+"     "+stringIntegerEntry.getValue());
            }
        }
    }
}

Arraylist嵌套HashMap

public class Test3 {
    public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<>();
        map.put("周瑜","小乔");
        map.put("吕布","貂蝉");
        HashMap<String, String> map1 = new HashMap<>();
        map1.put("郭靖","黄蓉");
        map1.put("杨过","小龙女");
        HashMap<String, String> map2 = new HashMap<>();
        map2.put("令狐冲","任盈盈");
        map2.put("林平之","岳灵珊");
        ArrayList<HashMap<String, String>> list = new ArrayList<>();
        list.add(map);
        list.add(map1);
        list.add(map2);
        for (HashMap<String, String> s : list) {
            Set<String> strings = s.keySet();
            for (String s1 : strings) {
                String s2 = s.get(s1);
                System.out.println("\t"+s1+"---"+s2);

            }
            System.out.println();
        }
    }
}

Collections工具类的概述和常见方法

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 Test4 {
    public static void main(String[] args) {
        //A:
        //案例演示:
        //模拟斗地主洗牌和发牌,牌没有排序
        //得有一副牌
        //生成54张牌放到牌盒里面
        String[] colors = {"♠", "♥", "♦", "♣"};
        String[] nums = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};
        HashMap<Integer, String> map = new HashMap<Integer, String>();
        ArrayList<Integer> list = new ArrayList<>();
        int index = 0;
        for (String num : nums) {
            for (String color : colors) {
                map.put(index, color.concat(num));
                list.add(index);
                index++;
            }
        }

            map.put(index, "☆");
            list.add(index);
            index++;
            map.put(index, "★");
            list.add(index);


            //洗牌
            Collections.shuffle(list);

            //发牌
            TreeSet<Integer> 高进 = new TreeSet<>();
            TreeSet<Integer> 刀仔 = new TreeSet<>();
            TreeSet<Integer> 星仔 = new TreeSet<>();
            TreeSet<Integer> 底牌 = new TreeSet<>();
            // 高进 = (ArrayList<String>) pokerBox.subList(0,17);
            // 高进 0  3 6 9
            //刀仔 1 4 7 10
            //  星仔 2 5 8 11
            for (int i = 0; i < list.size(); i++) {
                if (i >= list.size() - 3) {
                    底牌.add(list.get(i));
                } else if (i % 3 == 0) {
                    高进.add(list.get(i));
                } else if (i % 3 == 1) {
                    刀仔.add(list.get(i));
                } else {
                    星仔.add(list.get(i));
                }
            }



            //看牌
            lookPoker(map,高进,"高进");
            lookPoker(map,刀仔,"刀仔");
            lookPoker(map,星仔,"星仔");
            lookPoker(map,底牌,"底牌");



    }

    public static void lookPoker(HashMap<Integer, String> map, TreeSet<Integer> list, String name) {
        System.out.println(name);
        for (Integer s : list) {
            System.out.print(map.get(s));
        }
        System.out.println();
    }
}

Map中的键唯一,但是当存储自定义对象时,需要重写Hashcode和equals方法

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/156965.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • idea创建springboot父子工程_Springboot框架

    idea创建springboot父子工程_Springboot框架在本系列第一篇文章,我们讲解了如何在IDEA中搭建第一个SpringBoot项目:【SpringBoot】一、创建第一个SpringBoot项目,本篇文章,我们讲解如何在IDEA中搭建SpringBoot的父子Module工程项目1、Module工程项目简介多模块项目,适用于一些比较大的项目,通过合理的模块拆分,实现代码的复用,便于维护和管理。尤其是一些开源框架,也是采用多模块的方式,提供插件集成,用户可以根据需要配置指定的模块。2、创建一个SpringBoot项目就是创

    2022年10月13日
    3
  • unity3d让物体移动_3D怎么让物体不被渲染

    unity3d让物体移动_3D怎么让物体不被渲染Unity3D入门:简单的物体运动 我们来了解一下Translate的使用首先我们来看看场景的搭建:建一个立方体,加一个点光源。 我们要实现的就是让场景中的立方体延X轴嗖嗖的移动那么我们在Project新建一个js脚本Creat-&gt;Javascript键入代码functionUpdate(){    transform.Trans…

    2022年8月10日
    8
  • 使用CEfSharp之旅(6)拦截网络请求 截取get post response返回「建议收藏」

    使用CEfSharp之旅(6)拦截网络请求 截取get post response返回「建议收藏」主要是继承实现Cefsharp的IRquestHandler对象,废话不多说上代码:publicclassrequest:IRequestHandler{publiceventAction<string>msg;publiceventAction<string,object>…

    2022年9月2日
    10
  • ODS和EDW_csgo vac和ow的区别

    ODS和EDW_csgo vac和ow的区别企业运营数据仓储(ODS)和企业数据仓库(EDW)企业数据架构EDW主要为企业提供分析决策服务。ODS主要实现企业数据整合、共享和准实时运营监控等功能,ODS是EDW的一个有益的补充和扩展其中.ADB为应用数据库;A、B、C表示不同类型的数据流动:A表示操作环境中应用数据库之间的直接数据交换;B表示操作环境中应用数据库之间通

    2022年9月26日
    6
  • 2.5D RGBD 图像 深度学习

    2.5D RGBD 图像 深度学习RGBD=RGB+DepthMapRGB:RGB色彩模式是工业界的一种颜色标准,是通过对红®、绿(G)、蓝(B)三个颜色通道的变化以及它们相互之间的叠加来得到各式各样的颜色的,RGB即是代表红、绿、蓝三个通道的颜色,这个标准几乎包括了人类视力所能感知的所有颜色,是目前运用最广的颜色系统之一。DepthMap:在3D计算机图形中,DepthMap(深度图)是包含与视点的场景对象的表面的距离有关的信息的图像或图像通道。其中,DepthMap类似于灰度图像,只是它的每个像素值是传感器

    2022年9月18日
    2
  • 数据挖掘的预测建模_数据挖掘建模培训

    数据挖掘的预测建模_数据挖掘建模培训数据挖掘就是从大量的、不完全的、有噪声的、模糊的、随机的实际应用数据中,提取隐含在其中的、人们事先不知道的、但又是潜在有用的信息和知识的过程。听起来比较抽象,我们举个例子。傍晚小街路面上沁出微雨后的湿润,和煦的细风吹来,抬头看看天边的晚霞,嗯,明天又是一个好天气。走到水果摊旁,挑了个根蒂蜷缩、敲起来声音浊响的青绿西瓜,心里期待着享受这个好瓜。由路面微湿、微风、晚霞得出明天是个好天气。根蒂蜷缩、敲声浊响、色泽青绿推断出这是个好瓜,显然,我们是根据以往的经验来对未来或未知的事物做出预测。人可以根据经验对未来进行

    2025年9月12日
    4

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号