文章目录

  • JAVA集合——Map
  • Map的一些概念和特点:
  • Map集合的获取功能测试:
  • Map集合的遍历之键找值
  • Map集合的遍历之键值对
  • HashMap案例:
  • LinkedHashMap
  • TreeMap
  • HashMap和HasTable的区别:
  • Map案例演示:(统计字符串中每个字符出现的次数)
  • 集合嵌套之HashMap嵌套HashMap:
  • 集合嵌套之HashMap嵌套ArrayList:
  • 集合嵌套之ArrayList嵌套HashMap:
  • Map集合案例演示:(模拟斗地主洗牌和发牌)
  • Collections工具类的概述和常见方法讲解


JAVA集合——Map

Map的一些概念和特点:

  • 概念:对于这种键值映射关系的数据,一个键映射一个值,对于这种数据,JAVA给我们提供了另外一种容器,叫做Map集合,就是用来存储这种键值对的。
  • Map接口和Collection接口的不同:(Map是一个借口!)
    (1) Map是双列的,Collection是单列的
    (2) Map的键唯一,Collection的子体系Set是唯一的
    (3) Map集合的数据结构针对键有效,跟值无关;Collection集合的数据结构是针对元素有效
  • 注意:Map集合的数据结构只跟键有关。比如:HashMap键的数据结构是哈希表
  • Map接口的继承体系:

java map 和集合 java中map集合_数据结构

  • 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<K> keySet():获取集合中所有键的集合
	Collection<V> values():获取集合中所有值的集合
e:长度功能
	int size():返回集合中的键值对的对数
  • 使用方法:
public class MyTest2 {
    public static void main(String[] args) {
        HashMap<String, String> hm = new HashMap<>();
        //存储键值对
      /*  V put (K key, V value)
        在此映射中关联指定值与指定键。*/
        String s = hm.put("文章", "马伊琍");
        System.out.println(s);
        //键相同,值覆盖,当你第一次存储这个键值对时,返回的是null
        //当你第二次存储相同的键,但是值不同,就会发生键相同,值覆盖,返回的是这个键第一次的旧值
        String s1 = hm.put("文章", "姚笛");
        System.out.println(s1);
        hm.put("贾乃亮", "李小璐");
        hm.put("王宝强", "蓉儿");
        hm.put("陈羽凡", "白百合");
        hm.put("王大治", "董洁");
        hm.put("大朗", "金莲");

        System.out.println(hm);
    }
}
--------------
输出:
null
马伊琍
{贾乃亮=李小璐, 王大治=董洁, 文章=姚笛, 王宝强=蓉儿, 大朗=金莲, 陈羽凡=白百合}
  • HashSet 用的是HashMap来存储的。(怎么理解?键是在HashSet中存储的对象计算的hash数值,值是一个链表?)

Map集合的获取功能测试:

  • 示例:
public class MyTest {
    public static void main(String[] args) {
        HashMap<String, String> hm = new HashMap<>();
        //存储键值对
        String s = hm.put("文章", "马伊琍");
        hm.put("贾乃亮", "李小璐");
        hm.put("王宝强", "蓉儿");
        hm.put("陈羽凡", "白百合");
        hm.put("王大治", "董洁");
        hm.put("大朗", "金莲");
        //移除一个键值对
        String value = hm.remove("大朗");
        System.out.println(value);
        System.out.println(hm);
        //清空集合中所有的键值对
       // hm.clear();
        System.out.println(hm);
        boolean empty = hm.isEmpty(); //判断集合是否
        int size = hm.size();//获取集合的长度

        //判断集合中是否包含这个键
        System.out.println(hm.containsKey("贾乃亮"));

        //判断集合中是否包含这个值

        System.out.println(hm.containsValue("金莲"));
    }
}
------------
输出:
金莲
{贾乃亮=李小璐, 王大治=董洁, 文章=马伊琍, 王宝强=蓉儿, 陈羽凡=白百合}
{贾乃亮=李小璐, 王大治=董洁, 文章=马伊琍, 王宝强=蓉儿, 陈羽凡=白百合}
true
false

Map集合的遍历之键找值

  • 键找值思路
    (1) 获取所有键的集合
    (2) 遍历键的集合,获取到每一个键
    (3) 根据键找值
  • 示例:
public class MyTest {
    public static void main(String[] args) {
        HashMap<String, String> hm = new HashMap<>();
        //存储键值对
        String s = hm.put("文章", "马伊琍");
        hm.put("贾乃亮", "李小璐");
        hm.put("王宝强", "蓉儿");
        hm.put("陈羽凡", "白百合");
        hm.put("王大治", "董洁");
        hm.put("大朗", "金莲");

        //遍历map集合方式1 ,根据键找值
      /*  String value = hm.get("文章");
        System.out.println(value);*/
        Set<String> strings = hm.keySet(); //获取所有键的集合
        //遍历键集,根据键找值
        for (String key : strings) {
            System.out.println(key+"==="+hm.get(key));
        }

        //获取值的集合
        Collection<String> values = hm.values();
        System.out.println(values);
    }
}
---------------
输出:
贾乃亮===李小璐
王大治===董洁
文章===马伊琍
王宝强===蓉儿
大朗===金莲
陈羽凡===白百合
[李小璐, 董洁, 马伊琍, 蓉儿, 金莲, 白百合]
  • 特点:虽然,HashMap的存放顺序和添加顺序无关,但是其获得的键的集合和值的集合的顺序是一致的,这一点和Python的字典是一样的!

Map集合的遍历之键值对

  • 思路:把键值对,统一看做一个整体取出来,放到一个集合中。
public class MyTest2 {
    public static void main(String[] args) {
        HashMap<String, String> hm = new HashMap<>();
        //存储键值对
        String s = hm.put("文章", "马伊琍");
        hm.put("贾乃亮", "李小璐");// Node<K,V> getKey() getValue()
        hm.put("王宝强", "蓉儿");
        hm.put("陈羽凡", "白百合");
        hm.put("王大治", "董洁");
        hm.put("大朗", "金莲");

        //map集合的遍历方式2:把键找对,统一看作一个整体取出来,放到一个集合中
        //Map.Entry<String, String>
        /*接口 Map.Entry<K, V>
        K getKey ()
        返回与此项对应的键。
        V getValue ()
        返回与此项对应的值。*/

        Set<Map.Entry<String, String>> entries = hm.entrySet();
        for (Map.Entry<String, String> entry : entries) {
           // System.out.println(entry); Node
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key+"==="+value);
        }
    }
}
--------------------
输出:
贾乃亮===李小璐
王大治===董洁
文章===马伊琍
王宝强===蓉儿
大朗===金莲
陈羽凡===白百合

HashMap案例:

  • 概述:HashMap是键必须满足hash性质(若hashCode()的返回值一致,则认为是同一个对象,就进行置换功能)的Map集合。
  • HashMap集合键是String值是Student的案例:
    前提:由于String类重写了hashCode()和equals()方法,所以,两个字符串对象相互比较是可以判断时可以调用该方法来判断是否属于同一个键的。
-------------------(学生类)
public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
------------------(主函数)
public class MyTest2 {
    public static void main(String[] args) {
        //存储键是String 类型,值Student
        //Map 集合的数据结构只跟键有关
        HashMap<String, Student> hashMap = new HashMap<>();
        hashMap.put("s001", new Student("张三", 23));
        hashMap.put("s001", new Student("张三3333", 230));
        hashMap.put("s002", new Student("张三", 23));
        hashMap.put("s003", new Student("lisi", 29));
        hashMap.put("s005", new Student("王五", 28));
        hashMap.put("s006", new Student("赵六", 27));
        hashMap.put("s007", new Student("田七", 27));

        new HashSet<String>().add("abc");

        System.out.println(hashMap);
    }
}
-------
输出:
{s007=Student{name='田七', age=27}, s003=Student{name='lisi', age=29}, s006=Student{name='赵六', age=27}, s005=Student{name='王五', age=28}, s002=Student{name='张三', age=23}, s001=Student{name='张三3333', age=230}}
  • HashMap集合键是Student值是String的案例:
    注意:由于自定义对象没有重写equals()方法和hashCode()方法,所以得重写了该方法之后,才能保证HashMap键的唯一性。(否则,是根据初始超类Object中的的equals()方法和hashCode()方法返回的结果来进行判断的)
------------------------------(自定义学生类)
public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }



    @Override       //重点:
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age &&
                Objects.equals(name, student.name);
    }

    @Override     //重点:
    public int hashCode() {
        return Objects.hash(name, age);
    }
}
---------------------------------(主函数)
public class MyTest3 {
    public static void main(String[] args) {
        //存储键是Student 值是String
        HashMap<Student,String> hashMap = new HashMap<>();
        hashMap.put(new Student("张三", 23),"s001");
        hashMap.put(new Student("张三", 23), "s002");
        hashMap.put(new Student("张三", 23), "哈哈哈哈");
        hashMap.put( new Student("张三3333", 230), "s001");
        hashMap.put( new Student("张三", 23), "呵呵呵呵呵");
        hashMap.put( new Student("lisi", 29),"s001");
        hashMap.put( new Student("王五", 28), "s001");
        hashMap.put( new Student("赵六", 27), "s001");
        hashMap.put( new Student("田七", 27), "s001");

        System.out.println(hashMap);
    }
}
-------
输出:
{Student{name='张三', age=23}=呵呵呵呵呵, Student{name='lisi', age=29}=s001, Student{name='赵六', age=27}=s001, Student{name='田七', age=27}=s001, Student{name='张三3333', age=230}=s001, Student{name='王五', age=28}=s001}
  • 小结:Map类型的数据结构的存储顺序只能键有关,其键在存储的时候,会通过hash函数计算索引位置,其值都是通过键来获取的(键有序,就相当于值有序了!)。HashSet底部用的都是HashMap为底层数据结构,把HashSet中的数值当做HashMap的键存在HashMap中,值是用一个空的数据结构来存储的,这样就能够利用HashMap的键不重复的特性来造就HashSet无重复值的特性了!

LinkedHashMap

  • 概述: Map 接口的哈希表和链接列表实现,具有可预知的迭代顺序
  • 特点:
    a. 底层的数据结构是链表和哈希表,元素有序、并且唯一。(这个有序指的是与添加元素的顺序保持一致)
    b. 元素的有序性由链表数据结构保证,唯一性由哈希表数据结构保证
    c. Map集合的数据结构只和键有关。
  • 示例:
public class MyTest {
    public static void main(String[] args) {
       // LinkedHashSet
      //  LinkedHashMap 键唯一,且有序,键的数据结构是哈希表和链表,链表保证了有效,哈希表保证了唯一
        LinkedHashMap<String,String> hm = new LinkedHashMap<>();
        hm.put("贾乃亮", "李小璐");
        hm.put("贾乃亮", "李小璐2");
        hm.put("王宝强", "蓉儿");
        hm.put("陈羽凡", "白百合");
        hm.put("王大治", "董洁");
        hm.put("大朗", "金莲");

        hm.forEach(new BiConsumer<String, String>() {
            @Override
            public void accept(String key, String value) {
                System.out.println(key+"==="+value);
            }
        });

    }
}
--------------
输出:(这里可以看到,与输入顺序一致!)
贾乃亮===李小璐2
王宝强===蓉儿
陈羽凡===白百合
王大治===董洁
大朗===金莲

TreeMap

  • 概述:TreeMap: 键的数据结构是红黑树,可保证键的排序和唯一性
  • 特点:
    (1) 排序分为自然排序和比较器排序 (跟TreeSet一样,只不过在TreeMap中,只针对键有要求!)
    (2) 线程是不安全但效率比较高
  • 案例1:(自然排序——键是Integer值是String)
public class TreeMapDemo {
    public static void main(String[] args) {
        TreeMap<Integer, String> treeMap = new TreeMap<>();
        treeMap.put(1,"aaa");
        treeMap.put(10, "bbb");
        treeMap.put(6, "aaa");
        treeMap.put(13, "ccc");
        treeMap.put(120, "ddd");

        treeMap.forEach(new BiConsumer<Integer, String>() {
            @Override
            public void accept(Integer key, String s) {
                System.out.println(key+"==="+s);
            }
        });
        System.out.println("================================");
        treeMap.forEach((k,v)-> System.out.println(k+"=="+v));  // 简写形式:


    }
}
---------------
输出:
1===aaa
6===aaa
10===bbb
13===ccc
120===ddd
================================
1==aaa
6==aaa
10==bbb
13==ccc
120==ddd
  • 案例2:(自然排序——键是Student值是String)
----------------------(自定义学生类)
package org.westos.demo6;
import java.util.Objects;

public class Student implements Comparable<Student>{
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }


    @Override
    public int compareTo(Student stu) {
        int num=this.age-stu.age;
        int num2=num==0?this.name.compareTo(stu.name):num;

        return num2;
    }
}
--------------------(主函数)
public class MyTest3 {
    public static void main(String[] args) {
        //Map 集合的数据结构根键有关
        //键是二叉树
        TreeMap<Student, String> hashMap = new TreeMap<>();
        hashMap.put(new Student("张三", 23), "s001");
        hashMap.put(new Student("张三", 23), "s002");
        hashMap.put(new Student("张三", 23), "哈哈哈哈");
        hashMap.put(new Student("张三3333", 230), "s001");
        hashMap.put(new Student("张三", 23), "呵呵呵呵呵");
        hashMap.put(new Student("lisi", 29), "s001");
        hashMap.put(new Student("王五", 28), "s001");
        hashMap.put(new Student("赵六", 27), "s001");
        hashMap.put(new Student("田七", 27), "s001");

       // System.out.println(hashMap);
        hashMap.forEach(new BiConsumer<Student, String>() {
            @Override
            public void accept(Student student, String s) {
                System.out.println(student.getName()+"---"+student.getAge()+"====="+s);
            }
        });

    }
}
-------
输出:
张三---23=====呵呵呵呵呵
田七---27=====s001
赵六---27=====s001
王五---28=====s001
lisi---29=====s001
张三3333---230=====s001
  • 案例3:(比较器排序——键是Student值是String)
----------------------(自定义学生类:)
public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
----------------------(主函数:)
public class MyTest3 {
    public static void main(String[] args) {
        //Map 集合的数据结构根键有关
        //键是二叉树
        TreeMap<Student, String> hashMap = new TreeMap<>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                int num=s1.getName().length()-s2.getName().length();
                int num2=num==0?s1.getName().compareTo(s2.getName()):num;
                int num3=num2==0?s1.getAge()-s2.getAge():num2;


                return num3;
            }
        });
        hashMap.put(new Student("张三", 23), "s001");
        hashMap.put(new Student("张三", 230), "s002");
        hashMap.put(new Student("张三", 23), "哈哈哈哈");
        hashMap.put(new Student("张三3333", 230), "s001");
        hashMap.put(new Student("张三sdfsfsdfs", 23), "呵呵呵呵呵");
        hashMap.put(new Student("lisi", 29), "s001");
        hashMap.put(new Student("王五sdffffffffffffffffffffffffffffffffff", 28), "s001");
        hashMap.put(new Student("赵六ssss", 27), "s001");
        hashMap.put(new Student("田七", 27), "s001");

       // System.out.println(hashMap);
        hashMap.forEach(new BiConsumer<Student, String>() {
            @Override
            public void accept(Student student, String s) {
                System.out.println(student.getName()+"---"+student.getAge()+"====="+s);
            }
        });

    }
}
-----------
输出:(先根据Student对象的Name的长度排序,再按照compareTo,最后按照年龄进行排序!)
张三---23=====哈哈哈哈
张三---230=====s002
田七---27=====s001
lisi---29=====s001
张三3333---230=====s001
赵六ssss---27=====s001
张三sdfsfsdfs---23=====呵呵呵呵呵
王五sdffffffffffffffffffffffffffffffffff---28=====s001

HashMap和HasTable的区别:

  • 差异:
    (1)HashMap和Hashtable 底层数据结构都一样,都是哈希表。
    (2)HashMap 线程不安全,效率高 允许存储null值和null键。
    (3)ashtable 线程安全效率低 不允许存储null值和null键。
  • 示例:
public class MyTest {
    public static void main(String[] args) {
        //HashMap
        //Hashtable
        //HashMap和Hashtable 底层数据结构都一样,都是哈希表
        //HashMap 线程不安全,效率高 允许存储null值和null 键
        //Hashtable 线程安全效率低 不允许存储null值和null 键
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put(null,null);
        System.out.println(stringStringHashMap);

    /*    Hashtable<Object, Object> objectObjectHashtable = new Hashtable<>();
        objectObjectHashtable.put(null,null);*/   -----> 报错!
    }
}
----------
输出:
{null=null}

Map案例演示:(统计字符串中每个字符出现的次数)

  • 需求:“aababcabcdabcde”, 获取字符串中每一个字母出现的次数要求结果:a(5) b(4) c(3) d(2) e(1)*/
  • 示例:
public class MyTest2 {
    public static void main(String[] args) {
     /*   A:
        案例演示:
        需求:统计字符串中每个字符出现的次数
        "aababcabcdabcde", 获取字符串中每一个字母出现的次数要求结果:a(5) b(4) c(3) d(2) e(1)*/
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一段字符串");
        String str = sc.nextLine();
        //aababcabcdabcde

       // "a(5) b(4) c(3) d(2) e(1)"
        // 分析:a----5
        // b-----4
        //c-----3
        //d-----2
        //e-----1
        //上面的数据是键值对新式,那么我就可以使用双列存起来
        遍历集合拼串
        //难点在于我得统计每个字符出现的次数,以及把他们存到集合中
        HashMap<Character, Integer> map = new HashMap<>();  //这里用什么类型的map都可以!
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
           // aababcabcdabcde
            //统计字符个数,往集合中存
            if(!map.containsKey(ch)){
                map.put(ch,1);
            }else{
                Integer integer = map.get(ch);
                integer++;
                map.put(ch, integer); //键相同,值覆盖
            }
        }

        //遍历集合串
        StringBuilder sb = new StringBuilder();
        map.forEach(new BiConsumer<Character, Integer>() {
            @Override
            public void accept(Character character, Integer integer) {
                sb.append(character).append("(").append(integer).append(")");
            }
        });
        String s = sb.toString();
        System.out.println(s);
    }
}
-----------
输出:
请输入一段字符串
aababcabcdabcde
a(5)b(4)c(3)d(2)e(1)

集合嵌套之HashMap嵌套HashMap:

  • 案例演示:(集合嵌套之HashMap嵌套HashMap)
public class MyTest {
    public static void main(String[] args) {
        /**
         *     基础班
         *             张三 20
         *             李四 22
         *      就业班
         *             王五 21
         *             赵六 23
         *
         *             HashMap 嵌套 HashMap
         */

        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>> maxMap = new HashMap<>();
        maxMap.put("基础班",jcMap);
        maxMap.put("就业班", jyMap);

        //集合的遍历方式1:(通过键来找相应的数值)
        Set<String> strings = maxMap.keySet();
        for (String string : strings) {
            System.out.println(string);
            HashMap<String, Integer> stringIntegerHashMap = maxMap.get(string);
            Set<String> strings1 = stringIntegerHashMap.keySet();
            for (String s : strings1) {
                System.out.println("\t"+s+"\t"+stringIntegerHashMap.get(s));
            }
            System.out.println();
        }

        //集合的遍历方式2:(通过获取键值对来进行迭代)
        System.out.println("===================================");
        Set<Map.Entry<String, HashMap<String, Integer>>> entries = maxMap.entrySet();
        for (Map.Entry<String, HashMap<String, Integer>> entry : entries) {
            String key = entry.getKey();
            System.out.println(key);
            HashMap<String, Integer> value = entry.getValue();
            Set<Map.Entry<String, Integer>> entries1 = value.entrySet();
            for (Map.Entry<String, Integer> stringIntegerEntry : entries1) {
                String key1 = stringIntegerEntry.getKey();
                Integer value1 = stringIntegerEntry.getValue();
                System.out.println("\t" + key1 + "\t" + value1);
            }
            System.out.println();

        }

        System.out.println("------------------------------");
        //集合的遍历方式3:(通过迭代器来进行迭代获取!)
        maxMap.forEach(new BiConsumer<String, HashMap<String, Integer>>() {
            @Override
            public void accept(String s, HashMap<String, Integer> stringIntegerHashMap) {
                System.out.println(s);
                stringIntegerHashMap.forEach(new BiConsumer<String, Integer>() {
                    @Override
                    public void accept(String s, Integer integer) {
                        System.out.println("\t"+s+"\t"+integer);
                    }
                });
            }
        });

    }
}

集合嵌套之HashMap嵌套ArrayList:

  • 案例演示:集合嵌套之HashMap嵌套ArrayList
    (a) 假设HashMap集合的元素是ArrayList。有3个。
    (b) 每一个ArrayList集合的值是字符串。
public class MyTest2 {
    public static void main(String[] args) {
        /**
         *                三国演义
         *                    吕布
         *                    周瑜
         *                 笑傲江湖
         *                     令狐冲
         *                     林平之
         *                 神雕侠侣
         *                     郭靖
         *                     杨过
         */
        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>> maxMap = new HashMap<>();
        maxMap.put("三国演义",sgList);
        maxMap.put("笑傲江湖", xaList);
        maxMap.put("神雕侠侣", sdList);

        //遍历
        Set<Map.Entry<String, ArrayList<String>>> entries = maxMap.entrySet();
        for (Map.Entry<String, ArrayList<String>> entry : entries) {
            String key = entry.getKey();
            System.out.println(key);
            ArrayList<String> list = entry.getValue();
            for (String s :list) {
                System.out.println("\t"+s);
            }
            System.out.println();
        }


    }
}
----------
输出:
神雕侠侣
	尹志平
	郭靖

三国演义
	吕布
	周瑜

笑傲江湖
	令狐冲
	林平之

集合嵌套之ArrayList嵌套HashMap:

  • 案例演示:集合嵌套之ArrayList嵌套HashMap
    (a) 假设ArrayList集合的元素是HashMap。有3个。
    (b) 每一个HashMap集合的键和值都是字符串。
  • 示例:
public class MyTest3 {
    public static void main(String[] args) {
        /*
        周瑜-- - 小乔
        吕布-- - 貂蝉

        郭靖-- - 黄蓉
        杨过-- - 小龙女

        令狐冲-- - 任盈盈
        林平之-- - 岳灵珊

        小集合是HashMap
        大的集合是list

        List 嵌套 HashMap

         */
        HashMap<String, String> sgmap = new HashMap<>();
        sgmap.put("周瑜", "小乔");
        sgmap.put("吕布", "貂蝉");

        HashMap<String, String> sdmap = new HashMap<>();
        sdmap.put("郭靖", "黄蓉");
        sdmap.put("杨过", "小龙女");
        sdmap.put("杨过", "郭襄");

        HashMap<String, String> xamap = new HashMap<>();
        xamap.put("令狐冲", " 任盈盈");
        xamap.put("林平之", "岳灵珊");

        ArrayList<HashMap<String, String>> maxList = new ArrayList<>();
        maxList.add(sgmap);
        maxList.add(sdmap);
        maxList.add(xamap);

        //遍历
        for (HashMap<String, String> map : maxList) {
            Set<Map.Entry<String, String>> entries = map.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                String key = entry.getKey();
                String value = entry.getValue();
                System.out.println(key + "---------" + value);
            }
            System.out.println();
        }
    }
}
-----------
输出:
吕布---------貂蝉
周瑜---------小乔

杨过---------郭襄
郭靖---------黄蓉

令狐冲--------- 任盈盈
林平之---------岳灵珊

Map集合案例演示:(模拟斗地主洗牌和发牌)

  • 模拟斗地主洗牌和发牌并对牌进行排序的原理图解:

java map 和集合 java中map集合_System_02


  • * 实现:
public class Test1 {
    public static void main(String[] args) {
       /* A:
        案例演示:
        模拟斗地主洗牌和发牌,牌没有排序*/
        //首先得有一副牌
        //花色 A-K
        //创建一个牌盒子
        ArrayList<String> pokerBox = new ArrayList<>();
        //生成54张牌,放进排行
        String[] colors = {"♥", "♠", "♣", "♦"};
        String[] nums = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
        for (String color : colors) {
            for (String num : nums) {
                pokerBox.add(color.concat(num));
            }
        }
        //手动添加大小王
        pokerBox.add("☀");
        pokerBox.add("🌙");

        //建立对应的映射关系:
        HashMap<Integer, String> map = new HashMap<>();

        Integer x = 0;
        for (String box : pokerBox) {
            map.put(x++,box);
        }

        ArrayList<Integer> pokernum = new ArrayList<>();
        //得到对应的牌的序号:
        for (Integer s : map.keySet()) {
            pokernum.add(s);
        }

        //打乱:
        Collections.shuffle(pokernum);

        //给每个人发牌:(每个人的牌必须得有序)
        TreeSet<Integer> 高进 = new TreeSet<>();
        TreeSet<Integer> 刀仔 = new TreeSet<>();
        TreeSet<Integer> 星仔 = new TreeSet<>();
        TreeSet<Integer> 底牌 = new TreeSet<>();

        for (int i = 0; i < pokernum.size(); i++) {
            if(i>=pokernum.size()-3){
                底牌.add(pokernum.get(i));
            }else if(i%3 ==0){
                高进.add(pokernum.get(i));
            }else if(i%3==1){
                刀仔.add(pokernum.get(i));
            }else{
                星仔.add(pokernum.get(i));
            }
        }

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

    }

    private static void lookPoker(TreeSet<Integer> person, HashMap<Integer, String> map) {
        for (Integer integer : person) {
            System.out.print(map.get(integer)+"\t");
        }
        System.out.println();
    }

}
------------------
输出:
♥A	♥2	♥4	♥9	♥J	♥Q	♠A	♠3	♠10	♠Q	♣A	♣2	♣5	♣8	♦8	♦9	🌙	
♥5	♥7	♥8	♥K	♠6	♠8	♠J	♣3	♣4	♣6	♣10	♣K	♦4	♦6	♦7	♦10	☀	
♥3	♥6	♥10	♠2	♠4	♠5	♠7	♠9	♣7	♣9	♦A	♦2	♦3	♦5	♦J	♦Q	♦K	
♠K	♣J	♣Q

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

  • Collections类概述:针对集合操作的工具类(类似于数组类的工具类:Arrays)
  • Collections成员方法:
public static <T> void sort(List<T> list):					排序,默认按照自然顺序
public static <T> int binarySearch(List<?> list,T key):		二分查找
public static <T> T max(Collection<?> coll):				获取最大值
public static void reverse(List<?> list):					反转
public static void shuffle(List<?> list):					随机置换
  • 示例:
public class MyTest4 {
    public static void main(String[] args) {
        //针对Collection 集合 Java给我们提供了一个工具类
        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(20);
        integers.add(200);
        integers.add(20000);
        integers.add(20);
        integers.add(120);

        System.out.println(integers);
        //二分查找
        int i = Collections.binarySearch(integers, 20);
        System.out.println(i);
        //排序
        //integers.sort();
        Collections.sort(integers, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1-o2;
            }
        });
        System.out.println(integers);
      //获取集合中的最值
        Integer max = Collections.max(integers);
        System.out.println(max);
        Integer min = Collections.min(integers);
        System.out.println(min);
        //随机打乱集合中的元素顺序
        Collections.shuffle(integers);

        System.out.println(integers);

    }
}
------------
输出:
[20, 200, 20000, 20, 120]
0
[20, 20, 120, 200, 20000]
20000
20
[20000, 20, 200, 120, 20]