6、集合

集合体系结构

集合类的特点

提供一种存储空间可变的存储模型,存储的数据容量可以随时发生改变

集合类的体系图

 

 

Collection集合概述和基本使用

Collection集合概述

是单例集合的顶层接口,它表示一组对象,这些对象也称为Collection的元素

JDK 不提供此接口的任何直接实现,它提供更具体的子接口(如Set和List)实现

Collection集合基本使用 

import java.util.ArrayList;
import java.util.Collection;

public class CollectionDemo {
    public static void main(String[] args) {
        //创建Collection集合的对象
        Collection<String> c = new ArrayList<String>();

        //添加元素:boolean add(E e)
        c.add("hello");
        c.add("world");
        c.add("java");
        //输出集合对象
        System.out.println(c);
    }
}

Collection集合的常用方法

Collection集合的遍历

迭代器的介绍

迭代器,集合的专用遍历方式

Iterator iterator():返回此集合中元素的迭代器,通过集合的iterator()方法得到

迭代器是通过集合的iterator()方法得到的,所以我们说它是依赖于集合而存在的

Collection集合的遍历 

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class IteratorDemo {
    public static void main(String[] args) {
        //创建集合对象
        Collection<String> c = new ArrayList<String>();
        //添加元素
        c.add("hello");
        c.add("world");
        c.add("java");
        //Iterator<E> iterator():返回此集合中元素的迭代器,通过集合的iterator()方法得到
        Iterator<String> it = c.iterator();
        //用while循环改进元素的判断和获取
        while (it.hasNext()){
            String s = it.next();
            System.out.println(s);
        }
    }
}

集合使用步骤图解

使用步骤
集合的案例-Collection集合存储学生对象并遍历

创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合

代码实现
学生类
public class Student {
    private String name;
    private int age;

    public Student() {
    }

    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;
    }
}
测试类
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/*
    需求:
        创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合

    思路:
        1:定义学生类
        2:创建Collection集合对象
        3:创建学生对象
        4:把学生添加到集合
        5:遍历集合(迭代器方式)
 */
public class CollectionDemo {
    public static void main(String[] args) {
        //创建Collection集合对象
        Collection<Student> c = new ArrayList<Student>();

        //创建学生对象
        Student s1 = new Student("林青霞", 30);
        Student s2 = new Student("张曼玉", 35);
        Student s3 = new Student("王祖贤", 33);

        //把学生添加到集合
        c.add(s1);
        c.add(s2);
        c.add(s3);

        //遍历集合(迭代器方式)
        Iterator<Student> it = c.iterator();
        while (it.hasNext()) {
            Student s = it.next();
            System.out.println(s.getName() + "," + s.getAge());
        }

    }
}

List集合

List集合概述和特点

List集合概述

有序集合(也称为序列),用户可以精确控制列表中每个元素的插入位置。用户可以通过整数索引访问元素,并搜索列表中的元素

与Set集合不同,列表通常允许重复的元素

List集合特点

  1. 有索引

  2. 可以存储重复元素

  3. 元素存取有序

List集合的特有方法

集合的案例-List集合存储学生对象并遍历

创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合
代码实现
学生类
public class Student {
    private String name;
    private int age;

    public Student() {
    }

    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;
    }
}
测试类
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ListDemo {
    public static void main(String[] args) {
        //创建List集合对象
        List<Student> list = new ArrayList<Student>();
        //创建学生对象
        Student s1 = new Student("林青霞", 30);
        Student s2 = new Student("张曼玉", 35);
        Student s3 = new Student("王祖贤", 33);
        //把学生添加到集合
        list.add(s1);
        list.add(s2);
        list.add(s3);
        System.out.println(list);
        //迭代器方式
        Iterator<Student> it = list.iterator();
        while (it.hasNext()) {
            Student s = it.next();
            System.out.println(s.getName() + "," + s.getAge());
        }
        System.out.println("--------------------");
        //for循环方式
        for (int i = 0; i < list.size(); i++) {
            Student s = list.get(i);
            System.out.println(s.getName() + "," + s.getAge());
        }
    }
}

并发修改异常

出现的原因

迭代器遍历的过程中,通过集合对象修改了集合中的元素,造成了迭代器获取元素中判断预期修改值和实际修改值不一致,则会出现:ConcurrentModifificationException

解决的方案

用for循环遍历,然后用集合对象做对应的操作即可

示例代码

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ListDemo {
    public static void main(String[] args) {
        //创建集合对象
        List<String> list = new ArrayList<String>();
        //添加元素
        list.add("hello");
        list.add("world");
        list.add("java");
        //遍历集合,得到每一个元素,看有没有"world"这个元素,如果有,我就添加一 个"javaee"元素,请写代码实现
        Iterator<String> it = list.iterator();
//        while (it.hasNext()){
//            String s = it.next();
//            if (s.equals("world")){
//                list.add("javaee");
//            }
//        }
        for (int i = 0; i < list.size(); i++) {
            String s = list.get(i);
            if (s.equals("world")) {
                list.add("javaee");
            }
        }
        System.out.println(list);
    }
}

列表迭代器

ListIterator介绍

通过List集合的listIterator()方法得到,所以说它是List集合特有的迭代器

用于允许程序员沿任一方向遍历的列表迭代器,在迭代期间修改列表,并获取列表中迭代器的当前位置

示例代码
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class ListIteratorDemo {
    public static void main(String[] args) {
        //创建集合对象
        List<String> list = new ArrayList<String>();
        //添加元素 
        list.add("hello");
        list.add("world");
        list.add("java");
        //获取列表迭代器
        ListIterator<String> lit = list.listIterator();
        while (lit.hasNext()) {
            String s = lit.next();
            if (s.equals("world")) {
                lit.add("javaee");
            }
        }
        System.out.println(list);
    }
}

增强for循环

定义格式
for(元素数据类型 变量名 : 数组/集合对象名) { 
    循环体; 
}
示例代码
import java.util.ArrayList;
import java.util.List;

/*
    增强for:简化数组和Collection集合的遍历
        实现Iterable接口的类允许其对象成为增强型 for语句的目标
        它是JDK5之后出现的,其内部原理是一个Iterator迭代器

    格式:
        for(元素数据类型 变量名 : 数组或者Collection集合) {
            //在此处使用变量即可,该变量就是元素
        }
 */
public class ForDemo {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5};
        for(int i : arr) {
            System.out.println(i);
        }
        System.out.println("--------");

        String[] strArray = {"hello","world","java"};
        for(String s : strArray) {
            System.out.println(s);
        }
        System.out.println("--------");

        List<String> list = new ArrayList<String>();
        list.add("hello");
        list.add("world");
        list.add("java");

        for(String s : list) {
            System.out.println(s);
        }
        System.out.println("--------");

        //内部原理是一个Iterator迭代器
        /*
        for(String s : list) {
            if(s.equals("world")) {
                list.add("javaee"); //ConcurrentModificationException
            }
        }
        */
    }
}

数据结构

数据结构之栈和队列

栈结构:先进后出

队列结构:先进先出

数据结构之数组和链表

数组结构:查询快、增删慢

队列结构:查询慢、增删快

List集合的实现类

List集合子类的特点

ArrayList集合:底层是数组结构实现,查询快、增删慢

LinkedList集合:底层是链表结构实现,查询慢、增删快

集合的案例-ArrayList集合存储学生对象三种方式遍历

创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合
代码实现
学生类
public class Student {
    private String name;
    private int age;

    public Student() {
    }

    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;
    }
}
测试类
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/*
    需求:
        创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合

    思路:
        1:定义学生类
        2:创建List集合对象
        3:创建学生对象
        4:把学生添加到集合
        5:遍历集合
            迭代器:集合特有的遍历方式
            普通for:带有索引的遍历方式
            增强for:最方便的遍历方式
 */
public class ListDemo {
    public static void main(String[] args) {
        //创建List集合对象
        List<Student> list = new ArrayList<Student>();

        //创建学生对象
        Student s1 = new Student("林青霞", 30);
        Student s2 = new Student("张曼玉", 35);
        Student s3 = new Student("王祖贤", 33);

        //把学生添加到集合
        list.add(s1);
        list.add(s2);
        list.add(s3);

        //迭代器:集合特有的遍历方式
        Iterator<Student> it = list.iterator();
        while (it.hasNext()) {
            Student s = it.next();
            System.out.println(s.getName()+","+s.getAge());
        }
        System.out.println("--------");

        //普通for:带有索引的遍历方式
        for(int i=0; i<list.size(); i++) {
            Student s = list.get(i);
            System.out.println(s.getName()+","+s.getAge());
        }
        System.out.println("--------");

        //增强for:最方便的遍历方式
        for(Student s : list) {
            System.out.println(s.getName()+","+s.getAge());
        }
    }
}

LinkedList集合的特有功能

特有方法

 

 

import java.util.LinkedList;

/*
    LinkedList集合的特有功能:
        public void addFirst(E e):在该列表开头插入指定的元素
        public void addLast(E e):将指定的元素追加到此列表的末尾

        public E getFirst():返回此列表中的第一个元素
        public E getLast():返回此列表中的最后一个元素

        public E removeFirst():从此列表中删除并返回第一个元素
        public E removeLast():从此列表中删除并返回最后一个元素
 */
public class LinkedListDemo {
    public static void main(String[] args) {
        //创建集合对象
        LinkedList<String> linkedList = new LinkedList<String>();

        linkedList.add("hello");
        linkedList.add("world");
        linkedList.add("java");

//        public void addFirst(E e):在该列表开头插入指定的元素
//        public void addLast(E e):将指定的元素追加到此列表的末尾
//        linkedList.addFirst("javase");
//        linkedList.addLast("javaee");

//        public E getFirst():返回此列表中的第一个元素
//        public E getLast():返回此列表中的最后一个元素
//        System.out.println(linkedList.getFirst());
//        System.out.println(linkedList.getLast());

//        public E removeFirst():从此列表中删除并返回第一个元素
//        public E removeLast():从此列表中删除并返回最后一个元素
//        System.out.println(linkedList.removeFirst());
//        System.out.println(linkedList.removeLast());

        System.out.println(linkedList);
    }
}

Set集合

Set集合概述和特点

Set集合的特点

  • 元素存取无序

  • 没有索引、只能通过迭代器或增强for循环遍历

  • 不能存储重复元素

Set集合的基本使用

import java.util.HashSet;
import java.util.Set;

public class SetDemo {
    public static void main(String[] args) {
        //创建集合对象
        Set<String> set = new HashSet<String>();
        //添加元素
        set.add("hello");
        set.add("world");
        set.add("java");
        //不包含重复元素的集合
        set.add("world");
        System.out.println(set);

        //遍历
        for (String s : set) {
            System.out.println(s);
        }
    }
}

哈希值

哈希值:是JDK根据对象的地址或者字符串或者数字算出来的int类型的数值

如何获取哈希值:Object类中的public int hashCode():返回对象的哈希码值

哈希值的特点

  • 同一个对象多次调用hashCode()方法返回的哈希值是相同的

  • 默认情况下,不同对象的哈希值是不同的。而重写hashCode()方法,可以实现让不同对象的哈希值相同

获取哈希值的代码

学生类
public class Student {
    private String name;
    private int age;

    public Student() {
    }

    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;
    }
}
测试类
/*
    哈希值:
        是JDK根据对象的地址或者字符串或者数字算出来的int类型的数值

    Object类中有一个方法可以获取对象的哈希值
        public int hashCode():返回对象的哈希码值
 */
public class HashDemo {
    public static void main(String[] args) {
        //创建学生对象
        Student s1 = new Student("林青霞",30);

        //同一个对象多次调用hashCode()方法返回的哈希值是相同的
        System.out.println(s1.hashCode()); //1060830840
        System.out.println(s1.hashCode()); //1060830840
        System.out.println("--------");

        Student s2 = new Student("林青霞",30);

        //默认情况下,不同对象的哈希值是不相同的
        //通过方法重写,可以实现不同对象的哈希值是相同的
        System.out.println(s2.hashCode()); //2137211482
        System.out.println("--------");

        System.out.println("hello".hashCode()); //99162322
        System.out.println("world".hashCode()); //113318802
        System.out.println("java".hashCode()); //3254818

        System.out.println("world".hashCode()); //113318802
        System.out.println("--------");

        System.out.println("重地".hashCode()); //1179395
        System.out.println("通话".hashCode()); //1179395


    }
}

HashSet集合概述和特点

HashSet集合的特点

  • 底层数据结构是哈希表

  • 对集合的迭代顺序不作任何保证,也就是说不保证存储和取出的元素顺序一致

  • 没有带索引的方法,所以不能使用普通for循环遍历

  • 由于是Set集合,所以是不包含重复元素的集合

HashSet集合的基本使用
import java.util.HashSet;

public class HashSetDemo {
    public static void main(String[] args) {
        //创建集合对象
        HashSet<String> hs = new HashSet<String>();
        //添加元素
        hs.add("hello");
        hs.add("world");
        hs.add("java");
        hs.add("world");
        System.out.println(hs);
        //遍历
        for (String s : hs) {
            System.out.println(s);
        }
    }
}

HashSet集合保证元素唯一性源码分析

HashSet集合保证元素唯一性的原理

1.根据对象的哈希值计算存储位置

  • 如果当前位置没有元素则直接存入

  • 如果当前位置有元素存在,则进入第二步

2.当前元素的元素和已经存在的元素比较哈希值

  • 如果哈希值不同,则将当前元素进行存储

  • 如果哈希值相同,则进入第三步

3.通过equals()方法比较两个元素的内容

  • 如果内容不相同,则将当前元素进行存储

  • 如果内容相同,则不存储当前元素
HashSet集合保证元素唯一性的图解

 

常见数据结构之哈希表

HashSet集合存储学生对象并遍历

案例需求

创建一个存储学生对象的集合,存储多个学生对象,使用程序实现在控制台遍历该集合

要求:学生对象的成员变量值相同,我们就认为是同一个对象

代码实现
学生类
public class Student {
    private String name;
    private int age;

    public Student() {
    }

    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 boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Student student = (Student) o;

        if (age != student.age) return false;
        return name != null ? name.equals(student.name) : student.name == null;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }
}
测试类
import java.util.HashSet;

/*
    需求:
        创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合
        要求:学生对象的成员变量值相同,我们就认为是同一个对象

    思路:
        1:定义学生类
        2:创建HashSet集合对象
        3:创建学生对象
        4:把学生添加到集合
        5:遍历集合(增强for)
 */
public class HashSetDemo02 {
    public static void main(String[] args) {
        //创建HashSet集合对象
        HashSet<Student> hs = new HashSet<Student>();

        //创建学生对象
        Student s1 = new Student("林青霞", 30);
        Student s2 = new Student("张曼玉", 35);
        Student s3 = new Student("王祖贤", 33);

        Student s4 = new Student("王祖贤", 33);

        //把学生添加到集合
        hs.add(s1);
        hs.add(s2);
        hs.add(s3);
        hs.add(s4);

        //遍历集合(增强for)
        for (Student s : hs) {
            System.out.println(s.getName() + "," + s.getAge());
        }

    }
}

LinkedHashSet集合概述和特点

LinkedHashSet集合特点

  • 哈希表和链表实现的Set接口,具有可预测的迭代次序

  • 由链表保证元素有序,也就是说元素的存储和取出顺序是一致的

  • 由哈希表保证元素唯一,也就是说没有重复的元素

LinkedHashSet集合基本使用

import java.util.LinkedHashSet;

public class LinkedHashSetDemo {
    public static void main(String[] args) {
        //创建集合对象
        LinkedHashSet<String> lhs = new LinkedHashSet<String>();
        //添加元素
        lhs.add("hello");
        lhs.add("world");
        lhs.add("java");
        lhs.add("world");
        System.out.println(lhs);
        //遍历集合
        for (String s : lhs) {
            System.out.println(s);
        }
    }
}

Set集合排序

TreeSet集合概述和特点

TreeSet集合概述

  • 元素有序,可以按照一定的规则进行排序,具体排序方式取决于构造方法
    • TreeSet():根据其元素的自然排序进行排序
    • TreeSet(Comparator comparator) :根据指定的比较器进行排序
  • 没有带索引的方法,所以不能使用普通for循环遍历
  • 由于是Set集合,所以不包含重复元素的集合
TreeSet集合基本使用
import java.util.TreeSet;

public class TreeSetDemo01 {
    public static void main(String[] args) {
        //创建集合对象
        TreeSet<Integer> ts = new TreeSet<Integer>();
        //添加元素
        ts.add(10);
        ts.add(30);
        ts.add(20);
        ts.add(50);
        ts.add(40);
        ts.add(40);
        System.out.println(ts);
        //遍历集合
        for (Integer i : ts) {
            System.out.println(i);
        }
    }
}

自然排序Comparable的使用

案例需求

存储学生对象并遍历,创建TreeSet集合使用无参构造方法

要求:按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序

实现步骤

  1. 用TreeSet集合存储自定义对象,无参构造方法使用的是自然排序对元素进行排序的

  2. 自然排序,就是让元素所属的类实现Comparable接口,重写compareTo(To)方法

  3. 重写方法时,一定要注意排序规则必须按照要求的主要条件和次要条件来写

代码实现
学生类
public class Student implements Comparable<Student> {
    private String name;
    private int age;

    public Student() {
    }

    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 int compareTo(Student s) {
//        return 0;
//        return 1;
//        return -1;
        //按照年龄从小到大排序
       int num = this.age - s.age;
//        int num = s.age - this.age;
        //年龄相同时,按照姓名的字母顺序排序
       int num2 = num==0?this.name.compareTo(s.name):num;
        return num2;
    }
}
测试类
import java.util.TreeSet;

/*
    存储学生对象并遍历,创建集合使用无参构造方法
    要求:按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序
 */
public class TreeSetDemo02 {
    public static void main(String[] args) {
        //创建集合对象
        TreeSet<Student> ts = new TreeSet<Student>();

        //创建学生对象
        Student s1 = new Student("xishi", 29);
        Student s2 = new Student("wangzhaojun", 28);
        Student s3 = new Student("diaochan", 30);
        Student s4 = new Student("yangyuhuan", 33);

        Student s5 = new Student("linqingxia",33);
        Student s6 = new Student("linqingxia",33);

        //把学生添加到集合
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);
        ts.add(s6);

        //遍历集合
        for (Student s : ts) {
            System.out.println(s.getName() + "," + s.getAge());
        }
    }
}

成绩排序案例

案例需求

用TreeSet集合存储多个学生信息(姓名,语文成绩,数学成绩),并遍历该集合

要求:按照总分从高到低出现

代码实现

学生类

public class Student {
    private String name;
    private int chinese;
    private int math;

    public Student() {
    }

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

    public String getName() {
        return name;
    }

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

    public int getChinese() {
        return chinese;
    }

    public void setChinese(int chinese) {
        this.chinese = chinese;
    }

    public int getMath() {
        return math;
    }

    public void setMath(int math) {
        this.math = math;
    }

    public int getSum() {
        return this.chinese + this.math;
    }
}
测试类
import java.util.Comparator;
import java.util.TreeSet;

public class TreeSetDemo {
    public static void main(String[] args) {
        //创建TreeSet集合对象,通过比较器排序进行排序
        TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
//                int num = (s2.getChinese()+s2.getMath())-(s1.getChinese()+s1.getMath());
                //主要条件
                int num = s2.getSum() - s1.getSum();
                //次要条件
                int num2 = num == 0 ? s1.getChinese() - s2.getChinese() : num;
                int num3 = num2 == 0 ? s1.getName().compareTo(s2.getName()) : num2;
                return num3;
            }
        });

        //创建学生对象
        Student s1 = new Student("林青霞", 98, 100);
        Student s2 = new Student("张曼玉", 95, 95);
        Student s3 = new Student("王祖贤", 100, 93);
        Student s4 = new Student("柳岩", 100, 97);
        Student s5 = new Student("风清扬", 98, 98);

        Student s6 = new Student("左冷禅", 97, 99);
//        Student s7 = new Student("左冷禅", 97, 99);
        Student s7 = new Student("赵云", 97, 99);

        //把学生对象添加到集合
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);
        ts.add(s6);
        ts.add(s7);

        //遍历集合
        for (Student s : ts) {
            System.out.println(s.getName() + "," + s.getChinese() + "," + s.getMath() + "," + s.getSum());
        }
    }
}

不重复的随机数案例

编写一个程序,获取10个1-20之间的随机数,要求随机数不能重复,并在控制台输出
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;

public class SetDemo01 {
    public static void main(String[] args) {
        //创建Set集合对象
        //Set<Integer> set = new HashSet<Integer>();
        Set<Integer> set = new TreeSet<Integer>();
        //创建随机数对象
        Random r = new Random();
        //判断集合的长度是不是小于10
        while (set.size() < 10) {
            //产生一个随机数,添加到集合
            int number = r.nextInt(20) + 1;
            set.add(number);
        }
        System.out.println(set);
        //遍历集合
        for (Integer i : set) {
            System.out.println(i);
        }
    }
}

Map集合

Map集合概述和特点

Map集合概述
interface Map<K,V> K:键的类型;V:值的类型 1

Map集合的特点

  • 键值对映射关系

  • 一个键对应一个值

  • 键不能重复,值可以重复

  • 元素存取无序

Map集合的基本使用

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

public class MapDemo01 {
    public static void main(String[] args) {
        //创建集合对象
        Map<String, String> map = new HashMap<String, String>();
        //V put(K key, V value) 将指定的值与该映射中的指定键相关联
        map.put("a", "林青霞");
        map.put("b", "张曼玉");
        map.put("c", "王祖贤");
        map.put("c", "柳岩");
        //输出集合对象
        System.out.println(map);
    }
}

Map集合的基本功能

示例代码

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

public class MapDemo02 {
    public static void main(String[] args) {
        //创建集合对象
        Map<String,String> map = new HashMap<String,String>();
        //put(K key,V value):添加元素
        map.put("张无忌","赵敏");
        map.put("郭靖","黄蓉");
        map.put("杨过","小龙女");
        //remove(Object key):根据键删除键值对元素
        System.out.println( map.remove("张无忌"));
        System.out.println( map.remove("张无忌"));

        //void clear():移除所有的键值对元素
//         map.clear();

        //boolean containsKey(Object key):判断集合是否包含指定的键
        System.out.println(map.containsKey("郭靖"));
        System.out.println(map.containsKey("黄蓉"));

        //boolean isEmpty():判断集合是否为空
        System.out.println(map.isEmpty());

        //int size():集合的长度,也就是集合中键值对的个数
        System.out.println(map.size());

        System.out.println(map);
    }
}

Map集合的获取功能

示例代码

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MapDemo03 {
    public static void main(String[] args) {
        //创建集合对象
        Map<String, String> map = new HashMap<String, String>();
        //添加元素
        map.put("张无忌", "赵敏");
        map.put("郭靖", "黄蓉");
        map.put("杨过", "小龙女");

        //V get(Object key):根据键获取值
        System.out.println(map.get("张无忌"));
        System.out.println("-------------------");

        //Set<K> keySet():获取所有键的集合
        Set<String> keySet = map.keySet();
        for (String key: keySet){
            System.out.println(key);
        }
        System.out.println("-------------------");
        //Collection<V> values():获取所有值的集合
        Collection<String> values = map.values();
        for (String value:values){
            System.out.println(value);
        }
    }
}

Map集合的遍历

方式1

遍历思路

我们刚才存储的元素都是成对出现的,所以我们把Map看成是一个夫妻对的集合

  1. 把所有的丈夫给集中起来

  2. 遍历丈夫的集合,获取到每一个丈夫

  3. 根据丈夫去找对应的妻子

步骤分析

  1. 获取所有键的集合。用keySet()方法实现

  2. 遍历键的集合,获取到每一个键。用增强for实现

  3. 根据键去找值。用get(Object key)方法实现

代码实现

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

public class MapDemo04 {
    public static void main(String[] args) {
        //创建集合对象
        Map<String, String> map = new HashMap<String, String>();
        //添加元素
        map.put("张无忌", "赵敏");
        map.put("郭靖", "黄蓉");
        map.put("杨过", "小龙女");

        //获取所有键的集合。用keySet()方法实现
        Set<String> keys = map.keySet();
        //遍历键的集合,获取到每一个键。用增强for实现
        for (String key : keys) {
            //根据键去找值。用get(Object key)方法实现
            String value = map.get(key);
            System.out.println(key + "," + value);
        }

    }
}

方式2

遍历思路

我们刚才存储的元素都是成对出现的,所以我们把Map看成是一个夫妻对的集合

  1. 获取所有结婚证的集合

  2. 遍历结婚证的集合,得到每一个结婚证

  3. 根据结婚证获取丈夫和妻子

步骤分析

  1. 获取所有键值对对象的集合

    • Set<Map.Entry<K,V>> entrySet():获取所有键值对对象的集合
  2. 遍历键值对对象的集合,得到每一个键值对对象

    • 用增强for实现,得到每一个Map.Entry
  3. 根据键值对对象获取键和值

    • 用getKey()得到键

    • 用getValue()得到值

代码实现

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

public class MapDemo05 {
    public static void main(String[] args) {
        //创建集合对象
        Map<String, String> map = new HashMap<String, String>();
        //添加元素
        map.put("张无忌", "赵敏");
        map.put("郭靖", "黄蓉");
        map.put("杨过", "小龙女");
        //获取所有键值对对象的集合
        Set<Map.Entry<String, String>> entries = map.entrySet();
        //遍历键值对对象的集合,得到每一个键值对对象
        for (Map.Entry<String, String> me : entries) {
            //根据键值对对象获取键和值
            String key = me.getKey();
            String value = me.getValue();
            System.out.println(key + "," + value);
        }
    }
}

Map集合的案例

HashMap集合练习之键是String值是Student

创建一个HashMap集合,键是学号(String),值是学生对象(Student)。存储三个键值对元素,并遍历
代码实现
学生类
public class Student {
    private String name;
    private int age;

    public Student() {
    }

    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;
    }
}

测试类

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

/*
    需求:
        创建一个HashMap集合,键是学号(String),值是学生对象(Student)。存储三个键值对元素,并遍历

    思路:
        1:定义学生类
        2:创建HashMap集合对象
        3:创建学生对象
        4:把学生添加到集合
        5:遍历集合
            方式1:键找值
            方式2:键值对对象找键和值
 */
public class HashMapDemo {
    public static void main(String[] args) {
        //创建HashMap集合对象
        HashMap<String, Student> hm = new HashMap<String, Student>();

        //创建学生对象
        Student s1 = new Student("林青霞", 30);
        Student s2 = new Student("张曼玉", 35);
        Student s3 = new Student("王祖贤", 33);

        //把学生添加到集合
        hm.put("itheima001", s1);
        hm.put("itheima002", s2);
        hm.put("itheima003", s3);

        //方式1:键找值
        Set<String> keySet = hm.keySet();
        for (String key : keySet) {
            Student value = hm.get(key);
            System.out.println(key + "," + value.getName() + "," + value.getAge());
        }
        System.out.println("--------");

        //方式2:键值对对象找键和值
        Set<Map.Entry<String, Student>> entrySet = hm.entrySet();
        for (Map.Entry<String, Student> me : entrySet) {
            String key = me.getKey();
            Student value = me.getValue();
            System.out.println(key + "," + value.getName() + "," + value.getAge());
        }
    }
}

HashMap集合练习之键是Student值是String

案例需求

  • 创建一个HashMap集合,键是学生对象(Student),值是居住地 (String)。存储多个元素,并遍历。

  • 要求保证键的唯一性:如果学生对象的成员变量值相同,我们就认为是同一个对象

代码实现

学生类

public class Student {
    private String name;
    private int age;

    public Student() {
    }

    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 boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Student student = (Student) o;

        if (age != student.age) return false;
        return name != null ? name.equals(student.name) : student.name == null;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }
}
测试类
import java.util.HashMap;
import java.util.Set;

/*
    需求:
        创建一个HashMap集合,键是学生对象(Student),值是居住地 (String)。存储多个键值对元素,并遍历。
        要求保证键的唯一性:如果学生对象的成员变量值相同,我们就认为是同一个对象

    思路:
        1:定义学生类
        2:创建HashMap集合对象
        3:创建学生对象
        4:把学生添加到集合
        5:遍历集合
        6:在学生类中重写两个方法
            hashCode()
            equals()
 */
public class HashMapDemo {
    public static void main(String[] args) {
        //创建HashMap集合对象
        HashMap<Student, String> hm = new HashMap<Student, String>();

        //创建学生对象
        Student s1 = new Student("林青霞", 30);
        Student s2 = new Student("张曼玉", 35);
        Student s3 = new Student("王祖贤", 33);
        Student s4 = new Student("王祖贤", 33);

        //把学生添加到集合
        hm.put(s1, "西安");
        hm.put(s2, "武汉");
        hm.put(s3, "郑州");
        hm.put(s4, "北京");

        //遍历集合
        Set<Student> keySet = hm.keySet();
        for (Student key : keySet) {
            String value = hm.get(key);
            System.out.println(key.getName() + "," + key.getAge() + "," + value);
        }
    }
}

集合嵌套之ArrayList嵌套HashMap

案例需求

创建一个ArrayList集合,存储三个元素,每一个元素都是HashMap

每一个HashMap的键和值都是String,并遍历。

代码实现

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

/*
    需求:
        创建一个ArrayList集合,存储三个元素,每一个元素都是HashMap,每一个HashMap的键和值都是String,并遍历

    思路:
        1:创建ArrayList集合
        2:创建HashMap集合,并添加键值对元素
        3:把HashMap作为元素添加到ArrayList集合
        4:遍历ArrayList集合

    给出如下的数据:
        第一个HashMap集合的元素:
              孙策        大乔
              周瑜        小乔
        第二个HashMap集合的元素:
              郭靖        黄蓉
              杨过        小龙女
        第三个HashMap集合的元素:
              令狐冲    任盈盈
              林平之    岳灵珊
 */
public class ArrayListIncludeHashMapDemo {
    public static void main(String[] args) {
        //创建ArrayList集合
        ArrayList<HashMap<String, String>> array = new ArrayList<HashMap<String, String>>();

        //创建HashMap集合,并添加键值对元素
        HashMap<String, String> hm1 = new HashMap<String, String>();
        hm1.put("孙策", "大乔");
        hm1.put("周瑜", "小乔");
        //把HashMap作为元素添加到ArrayList集合
        array.add(hm1);

        HashMap<String, String> hm2 = new HashMap<String, String>();
        hm2.put("郭靖", "黄蓉");
        hm2.put("杨过", "小龙女");
        //把HashMap作为元素添加到ArrayList集合
        array.add(hm2);

        HashMap<String, String> hm3 = new HashMap<String, String>();
        hm3.put("令狐冲", "任盈盈");
        hm3.put("林平之", "岳灵珊");
        //把HashMap作为元素添加到ArrayList集合
        array.add(hm3);

        //遍历ArrayList集合
        for (HashMap<String, String> hm : array) {
            Set<String> keySet = hm.keySet();
            for (String key : keySet) {
                String value = hm.get(key);
                System.out.println(key + "," + value);
            }
        }
    }
}

集合嵌套之HashMap嵌套ArrayList

案例需求

创建一个HashMap集合,存储三个键值对元素,每一个键值对元素的键是String,值是ArrayList

每一个ArrayList的元素是String,并遍历。

代码实现

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

/*
    需求:创建一个HashMap集合,存储三个键值对元素,每一个键值对元素的键是String,值是ArrayList,
         每一个ArrayList的元素是String,并遍历

    思路:
        1:创建HashMap集合
        2:创建ArrayList集合,并添加元素
        3:把ArrayList作为元素添加到HashMap集合
        4:遍历HashMap集合

    给出如下的数据:
        第一个ArrayList集合的元素:(三国演义)
              诸葛亮
              赵云
        第二个ArrayList集合的元素:(西游记)
              唐僧
              孙悟空
        第三个ArrayList集合的元素:(水浒传)
              武松
              鲁智深
*/
public class HashMapIncludeArrayListDemo {
    public static void main(String[] args) {
        //创建HashMap集合
        HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();

        //创建ArrayList集合,并添加元素
        ArrayList<String> sgyy = new ArrayList<String>();
        sgyy.add("诸葛亮");
        sgyy.add("赵云");
        //把ArrayList作为元素添加到HashMap集合
        hm.put("三国演义",sgyy);

        ArrayList<String> xyj = new ArrayList<String>();
        xyj.add("唐僧");
        xyj.add("孙悟空");
        //把ArrayList作为元素添加到HashMap集合
        hm.put("西游记",xyj);

        ArrayList<String> shz = new ArrayList<String>();
        shz.add("武松");
        shz.add("鲁智深");
        //把ArrayList作为元素添加到HashMap集合
        hm.put("水浒传",shz);

        //遍历HashMap集合
        Set<String> keySet = hm.keySet();
        for(String key : keySet) {
            System.out.println(key);
            ArrayList<String> value = hm.get(key);
            for(String s : value) {
                System.out.println("\t" + s);
            }
        }
    }
}

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

案例需求

键盘录入一个字符串,要求统计字符串中每个字符串出现的次数。

举例:键盘录入“aababcabcdabcde” 在控制台输出:“a(5)b(4)c(3)d(2)e(1)”

代码实现

import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;

/*
    需求:
        键盘录入一个字符串,要求统计字符串中每个字符串出现的次数。
        举例:键盘录入“aababcabcdabcde”    在控制台输出:“a(5)b(4)c(3)d(2)e(1)”

    思路:
        1:键盘录入一个字符串
        2:创建HashMap集合,键是Character,值是Integer
        3:遍历字符串,得到每一个字符
        4:拿得到的每一个字符作为键到HashMap集合中去找对应的值,看其返回值
            如果返回值是null:说明该字符在HashMap集合中不存在,就把该字符作为键,1作为值存储
            如果返回值不是null:说明该字符在HashMap集合中存在,把该值加1,然后重新存储该字符和对应的值
        5:遍历HashMap集合,得到键和值,按照要求进行拼接
        6:输出结果
 */
public class HashMapDemo {
    public static void main(String[] args) {
        //键盘录入一个字符串
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String line = sc.nextLine();

        //创建HashMap集合,键是Character,值是Integer
//        HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
        TreeMap<Character, Integer> hm = new TreeMap<Character, Integer>();

        //遍历字符串,得到每一个字符
        for (int i = 0; i < line.length(); i++) {
            char key = line.charAt(i);

            //拿得到的每一个字符作为键到HashMap集合中去找对应的值,看其返回值
            Integer value = hm.get(key);

            if (value == null) {
                //如果返回值是null:说明该字符在HashMap集合中不存在,就把该字符作为键,1作为值存储
                hm.put(key,1);
            } else {
                //如果返回值不是null:说明该字符在HashMap集合中存在,把该值加1,然后重新存储该字符和对应的值
                value++;
                hm.put(key,value);
            }
        }

        //遍历HashMap集合,得到键和值,按照要求进行拼接
        StringBuilder sb = new StringBuilder();

        Set<Character> keySet = hm.keySet();
        for(Character key : keySet) {
            Integer value = hm.get(key);
            sb.append(key).append("(").append(value).append(")");
        }

        String result = sb.toString();

        //输出结果
        System.out.println(result);
    }
}

Collections集合工具类

Collections概述和使用

Collections类的作用:是针对集合操作的工具类

Collections类常用方法

示例代码

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CollectionsDemo01 {
    public static void main(String[] args) {
        //创建集合对象
        List<Integer> list = new ArrayList<Integer>();
        //添加元素
        list.add(20);
        list.add(40);
        list.add(30);
        list.add(50);
        list.add(10);

        //public static <T extends Comparable<? super T>> void sort•(List<T> list):将指定的列表按升序排序
        Collections.sort(list);

        //public static void reverse•(List<?> list):反转指定列表中元素的顺序
        Collections.reverse(list);

        //public static void shuffle•(List<?> list):使用默认的随机源随机排列指定的列 表
        Collections.shuffle(list);
        System.out.println(list);
    }
}

ArrayList集合存储学生并排序

案例需求

  • ArrayList存储学生对象,使用Collections对ArrayList进行排序

  • 要求:按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序

代码实现

学生类 

public class Student {
    private String name;
    private int age;

    public Student() {
    }

    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;
    }
}
测试类
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/*
    需求:
        ArrayList存储学生对象,使用Collections对ArrayList进行排序
        要求:按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序

    思路:
        1:定义学生类
        2:创建ArrayList集合对象
        3:创建学生对象
        4:把学生添加到集合
        5:使用Collections对ArrayList集合排序
        6:遍历集合
 */
public class CollectionsDemo02 {
    public static void main(String[] args) {
        //创建ArrayList集合对象
        ArrayList<Student> array = new ArrayList<Student>();

        //创建学生对象
        Student s1 = new Student("linqingxia", 30);
        Student s2 = new Student("zhangmanyu", 35);
        Student s3 = new Student("wangzuxian", 33);
        Student s4 = new Student("liuyan", 33);

        //把学生添加到集合
        array.add(s1);
        array.add(s2);
        array.add(s3);
        array.add(s4);

        //使用Collections对ArrayList集合排序
        //sort​(List<T> list, Comparator<? super T> c)
        Collections.sort(array, 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;
            }
        });

        //遍历集合
        for (Student s : array) {
            System.out.println(s.getName() + "," + s.getAge());
        }

    }
}

 

posted @ 2021-09-06 17:30  he。  阅读(60)  评论(0)    收藏  举报