集合框架详解之Set、Map接口与实现类

集合框架

1.Set集合

1.1Set集合概述

  • Set实现类:HashSet类、TreeSet类

  • 特点:无序、无下标、元素不可重复

  • 方法:全部继承自Collection中的方法

1.11 Set接口的使用简单代码演示

package collection.demo03;

import java.util.HashSet;
import java.util.Iterator;
/**
 * 测试Set接口的使用
 * 特点:1.无序,没有下标;2.不能重复
 * 1.添加数据
 * 2.删除数据
 * 3.遍历【重点】
 * 4.判断
 */
public class SetTest1 {
    public static void main(String[] args) {
       //新建集合
        HashSet<String> stringHashSet = new HashSet<>();

        //添加数据
        stringHashSet.add("许巍");
        stringHashSet.add("赵雷");
        stringHashSet.add("郑钧");
        stringHashSet.add("赵照");
        System.out.println(stringHashSet.size());
        System.out.println(stringHashSet.toString());//无序输出

        System.out.println(stringHashSet.add("赵照"));//false,这个重复数没有放入到集合中
        System.out.println(stringHashSet.size());




        //删除数据
        stringHashSet.remove("郑钧");
        System.out.println(stringHashSet.size());
        System.out.println(stringHashSet.toString());


        //遍历数据
        //3.1 使用增强for
        for (String s : stringHashSet) {
            System.out.println(s);
        }

        //3.2 使用迭代器
        Iterator<String> iterator = stringHashSet.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        //判断数据
        System.out.println(stringHashSet.isEmpty());
        System.out.println(stringHashSet.contains("赵雷"));


    }
}





运行结果

4
[赵雷, 赵照, 许巍, 郑钧]
false
4
3
[赵雷, 赵照, 许巍]
赵雷
赵照
许巍
赵雷
赵照
许巍
false
true



1.2 Set实现类->HashSet

  • HashSet:

    • 存储结构:哈希表(数组+链表+红黑树)
  • 存储过程(重复依据):

    • (1).根据hashCode计算保存的位置,如果位置为空,直接保存,若不为空,进行第二步

    • (2).再执行equals方法,如果equals为true,则认为是重复,否则形成链表

    • HashSet底层就是利用HashMap来完成的。

1.21 HashSet集合的使用代码演示:

package collection.demo03;

import java.util.Objects;

/**
 * 人类
 */
public class Person implements Comparable<Person>{
    private String name;
    private int age;

    public Person() {
    }

    public Person(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;
        Person person = (Person) o;
        return age == person.age &&
                Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        //底层是31原因
        //(1)31是质数,可以减少散列冲突(使得计算的哈希值尽量不一样);
        //(2)可以提高执行效率(31*i = (i << 5) - i);
        return Objects.hash(name, age);
    }

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

   //比较规则:先按姓名比再按年龄比
    @Override
    public int compareTo(Person o) {
        int n1=this.getName().compareTo(o.getName());
        int n2=this.age-o.getAge();
        return n1==0?n2:n1;
    }
}


package collection.demo03;

import java.util.HashSet;
import java.util.Iterator;

/**
 * HashSet集合的使用
 * 存储结构:哈希表(数组+链表+红黑树)
 * 1.添加元素
 * 2.删除元素
 * 3.遍历
 * 4.判断
 *
 *存储过程(重复依据)
 *(1)基于HashCode计算元素存放位置。如果此位置为空,则直接保存,如果不为空执行第二步
 * 2)再执行equals方法,如果equals方法为true,则认为是重复,拒绝后者存入,否则,形成链表
 *
 *
 */
public class HashSetTest1 {
    public static void main(String[] args) {

        //创建集合
        HashSet<Person> personHashSet = new HashSet<>();
        //1.添加元素
        Person p1 = new Person("张无忌", 21);
        Person p2 = new Person("郭靖", 21);
        Person p3 = new Person(";令狐冲", 21);
        Person p4 = new Person("胡斐", 21);

        personHashSet.add(p1);
        personHashSet.add(p2);
        personHashSet.add(p3);
        personHashSet.add(p4);

        System.out.println(personHashSet.size());
        System.out.println(personHashSet.toString());
        //重复 不再添加
        System.out.println(personHashSet.add(p1));//false
        //直接new一个相同属性的对象,依然会被添加,相当于内存中开辟了新的内存地址。
        //这样添加的元素可以添加进去 为了避免这种情况 可以重写 hashcode方法来避免这种情况
        //重写后  由name age决定hashcode
        System.out.println(personHashSet.add(new Person("胡斐", 21)));//false

        System.out.println(personHashSet.toString());

        //2.删除
        //personHashSet.remove(p4);
        personHashSet.remove(new Person("胡斐", 21));
        System.out.println(personHashSet.toString());

        //3.遍历
        //增强for
        System.out.println("============================");
        for (Person person : personHashSet) {
            System.out.println(person);
        }

        //使用迭代器
        System.out.println("----------------------------");
        Iterator<Person> iterator = personHashSet.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }

        //4.判断
        System.out.println(personHashSet.isEmpty());
        //注:假如相同属性便认为是同一个对象,该怎么做?
        System.out.println(personHashSet.contains(new Person("郭靖", 21)));//true 因为重写了hashcode和equals


    }
}

运行结果

4
[Person{name=';令狐冲', age=21}, Person{name='胡斐', age=21}, Person{name='张无忌', age=21}, Person{name='郭靖', age=21}]
false
false
[Person{name=';令狐冲', age=21}, Person{name='胡斐', age=21}, Person{name='张无忌', age=21}, Person{name='郭靖', age=21}]
[Person{name=';令狐冲', age=21}, Person{name='张无忌', age=21}, Person{name='郭靖', age=21}]
============================
Person{name=';令狐冲', age=21}
Person{name='张无忌', age=21}
Person{name='郭靖', age=21}
----------------------------
Person{name=';令狐冲', age=21}
Person{name='张无忌', age=21}
Person{name='郭靖', age=21}
false
true



1.3 List实现类->TreeSet

  • TreeSet:
    • 基于排序顺序实现不重复

    • 实现了SortedSet接口,对集合元素自动排序

    • 元素对象的类型必须实现Comparable接口,指定排序规则。

    • 通过CompareTo方法确定是否为重复元素

1.31 TreeSet的基本使用代码演示:

package collection.demo03;

import java.util.Iterator;
import java.util.TreeSet;
/**
 * TreeSet的基本使用:默认按照字典表排序
 * 存储结构:红黑树
 *
 */
public class TreeSetTest1 {
    public static void main(String[] args) {

        //创建集合
        TreeSet<String > stringTreeSet = new TreeSet<String >();

        //1.添加元素
        stringTreeSet.add("hello");
        stringTreeSet.add("abcd");
        stringTreeSet.add("world");
        stringTreeSet.add("xyz");

        System.out.println(stringTreeSet.size());
        System.out.println(stringTreeSet.toString());
        //2.删除
        stringTreeSet.remove("hello");
        System.out.println(stringTreeSet.size());
        System.out.println(stringTreeSet.toString());

        //3.遍历
        //增强for
        for (String s : stringTreeSet) {
            System.out.println(s);
        }

        //使用迭代器
        Iterator<String> iterator = stringTreeSet.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        //4.判断
        System.out.println(stringTreeSet.contains("abc"));
        System.out.println(stringTreeSet.isEmpty());

    }
}


运行结果

4
[abcd, hello, world, xyz]
3
[abcd, world, xyz]
abcd
world
xyz
abcd
world
xyz
false
false

1.32 TreeSet保存对象数据comparator实现定制比较代码演示:

package collection.demo03;

import java.util.Objects;

/**
 * 人类
 */
public class Person implements Comparable<Person>{
    private String name;
    private int age;

    public Person() {
    }

    public Person(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;
        Person person = (Person) o;
        return age == person.age &&
                Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        //底层是31原因
        //(1)31是质数,可以减少散列冲突(使得计算的哈希值尽量不一样);
        //(2)可以提高执行效率(31*i = (i << 5) - i);
        return Objects.hash(name, age);
    }

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

   //比较规则:先按姓名比再按年龄比
    @Override
    public int compareTo(Person o) {
        int n1=this.getName().compareTo(o.getName());
        int n2=this.age-o.getAge();
        return n1==0?n2:n1;
    }
}


package collection.demo03;

import java.util.Iterator;
import java.util.TreeSet;
/**
 *
 *  * TreeSet保存数据:添加元素为对象操作
 *  * 存储结构:红黑树
 *  * 元素必须实现Comparable接口 自定义比较方式
 *  * CompareTo方法返回值为 0 则认为是重复元素
 *
 *comparator 实现定制比较
 */
public class TreeSetTest2 {
    public static void main(String[] args) {
        //创建集合
        TreeSet<Person> personTreeSet = new TreeSet<>();

        //1.添加元素
        Person p1 = new Person("刘德华", 22);
        Person p2 = new Person("郭富城", 23);
        Person p3 = new Person("古天乐", 24);
        Person p4 = new Person("古天乐", 25);
        personTreeSet.add(p1);
        personTreeSet.add(p2);
        personTreeSet.add(p3);
        personTreeSet.add(p3);
        personTreeSet.add(p4);

        System.out.println(personTreeSet.size());
        System.out.println(personTreeSet.toString());

        //2.删除
        personTreeSet.remove(p4);
        System.out.println(personTreeSet.toString());

        //3.遍历
        //增强for
        for (Person person : personTreeSet) {
            System.out.println(person);
        }

        //使用迭代器Iterator
        Iterator<Person> iterator = personTreeSet.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }

        //4.判断
        System.out.println(personTreeSet.contains(new Person("古天乐", 24)));

    }
}

运行结果

4
[Person{name='刘德华', age=22}, Person{name='古天乐', age=24}, Person{name='古天乐', age=25}, Person{name='郭富城', age=23}]
[Person{name='刘德华', age=22}, Person{name='古天乐', age=24}, Person{name='郭富城', age=23}]
Person{name='刘德华', age=22}
Person{name='古天乐', age=24}
Person{name='郭富城', age=23}
Person{name='刘德华', age=22}
Person{name='古天乐', age=24}
Person{name='郭富城', age=23}
true


1.33 TreeSet的集合使用定制比较器Comparator代码演示:

package collection.demo03;

import java.util.Comparator;
import java.util.TreeSet;
/**
 * 还有一种定制比较器Comparator 不需要对对象类实现Comparable
 * TreeSet集合的实现定制比较
 * Comparator:实现定制比较(比较器)
 * Comparable:可比较的
 *
 */
public class ComparatorTest {
    public static void main(String[] args) {

        //创建集合 并指定比较规则
        TreeSet<Person> people = new TreeSet<>(new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                int n1=o1.getAge()-o2.getAge();
                int n2=o1.getName().compareTo(o2.getName());
                return n1==0?n2:n1;
            }
        });

        //1.添加元素
        Person p1 = new Person("hello", 21);
        Person p2 = new Person("lisi", 20);
        Person p3 = new Person("zhangsan", 20);
        Person p4 = new Person("hello", 22);

        people.add(p1);
        people.add(p2);
        people.add(p3);
        people.add(p4);
        System.out.println(people.toString());

        //people.remove(p4);
        people.remove(new Person("hello",22));//也可以删除 我们重写的compareTo方法比较的是name和age*/
        System.out.println(people.size());
        System.out.println(people.toString());

    }
}


运行结果

[Person{name='lisi', age=20}, Person{name='zhangsan', age=20}, Person{name='hello', age=21}, Person{name='hello', age=22}]
3
[Person{name='lisi', age=20}, Person{name='zhangsan', age=20}, Person{name='hello', age=21}]



1.34 用TreeSet实现字符串长度的比较案例代码演示:

package collection.demo03;

import java.util.Comparator;
import java.util.TreeSet;
/**
 * treeSet的使用
 * comparator自制
 * 使用treeSet 实现字符串长度的比较,若字符串的长相同,则按照默认字典排序
 * comparator 实现定制比较
 */
public class Demo {
    public static void main(String[] args) {

        //创建集合 并指定比较规则
        TreeSet<String> stringTreeSet = new TreeSet<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                int n1=o1.length()-o2.length();
                int n2=o1.compareTo(o2);
                return n1==0?n2:n1;
            }
        });

        //添加元素
        stringTreeSet.add("xian");
        stringTreeSet.add("nanjing");
        stringTreeSet.add("beijing");
        stringTreeSet.add("shijiazhuang");
        stringTreeSet.add("huludao");
        stringTreeSet.add("sanya");
        stringTreeSet.add("xiamen");

        System.out.println(stringTreeSet.toString());



    }
}



运行结果

[xian, sanya, xiamen, beijing, huludao, nanjing, shijiazhuang]

2. Map集合

2.1 Map集合概述

  • 实现类:Hashtable类、HashMap类、TreeMap类
  • Map接口的特点
    • (1)用于存储任意键值对(key - value)
    • (2)键:无序、无下标、不允许重复(唯一)
    • (3)值:无序、无下标、允许重复
    • 总结特点:存储一堆数据(Key-value),无序,无下标,键不可重复,值可重复。
  • 方法:
    • 增加:put(K key, V value)

    • 删除:clear() remove(Object key) remove(Object key, Object value)

    • 修改:replace(K key, V value)

    • 查看:entry(K k, V v) entrySet() get(Object key) keySet() size() values()

    • 判断:containsKey(Object key) containsValue(Object value) equals(Object o) isEmpty()

    • V put(K key,V value)//将对象存放到集合中,关联键值。key重复则覆盖原有值

    • Object get(Obeject key)//根据键获取对应的值

    • KeySet()//返回所有key;

    • Set<Map.Entry<K,V>> entrySet()//键值匹配的set集合

    • Collection<V> values()//返回包含所有值的Collection集合

2.11 ** Map接口的使用简单代码演示**

package collection.demo04;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
 * Map接口的使用
 * 特点:使用的键值对,key 无序、无下标、不可以重复 value 无序、无下标、可以重复 无序
 *
 */
public class MapTest {
    public static void main(String[] args) {
        //创建Map集合
        Map<String ,String> stringHashMap = new HashMap<>();

        //1.添加元素

          stringHashMap.put("CHN","中国");
          stringHashMap.put("AUS"," 澳大利亚");
          stringHashMap.put("JP","日本");
          stringHashMap.put("KR","韩国");

          System.out.println(stringHashMap.size());
          System.out.println(stringHashMap.toString());


        //2.删除元素
        stringHashMap.remove("KR");
        System.out.println(stringHashMap.size());
        System.out.println(stringHashMap.toString());

        //遍历
        //使用keySet
        System.out.println("======================");
        //Set<String> strings = stringHashMap.keySet();//可以省略,不需要引用
        for (String string : stringHashMap.keySet()) {
            System.out.println(string+"......."+stringHashMap.get(string));
        }

        //使用entrySet()方法
        System.out.println("======================");
        Set<Map.Entry<String, String>> entries = stringHashMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            System.out.println(entry.getKey()+":"+entry.getValue());
        }

        //使用迭代器
        System.out.println("======================");
        Iterator<Map.Entry<String, String>> iterator = stringHashMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, String> next = iterator.next();
            System.out.println(next.getKey()+":"+next.getValue());
        }

        //判断
        System.out.println(stringHashMap.containsKey("CHN"));
        System.out.println(stringHashMap.containsValue("中国"));


    }
}




运行结果

4
{JP=日本, KR=韩国, CHN=中国, AUS= 澳大利亚}
3
{JP=日本, CHN=中国, AUS= 澳大利亚}
======================
JP.......日本
CHN.......中国
AUS....... 澳大利亚
======================
JP:日本
CHN:中国
AUS: 澳大利亚
======================
JP:日本
CHN:中国
AUS: 澳大利亚
true
true


2.2 Map实现类->HashMap

  • HashMap:

    • JDK1.2版本,线程不安全,运行效率快;允许用null作为key或是value。
  • 特点:无序、唯一,按照key进行总结的,因为底层key遵照哈希表的结构(数组+链表)

  • 哈希表原理:比如放入这个集合的数据对应的那个类:必须重写hasCode方法和equals方法。

2.21 HashMap的使用代码演示

package collection.demo04;

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

    public Student() {
    }

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

    public String getName() {
        return name;
    }

    public int getStuNo() {
        return stuNo;
    }

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

    public void setStuNo(int stuNo) {
        this.stuNo = stuNo;
    }



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

    @Override
    public int compareTo(Student o) {
        /*
        int num1 = this.name.compareTo(o.name);
        int num2 = this.stuNo - o.stuNo;
        return num2 == 0 ? num1 : num2;
        */
        int n1=this.stuNo-o.getStuNo();
        return n1;

    }
}



package collection.demo04;

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

/**
 * HashMap的使用
 * 存储结构:哈希表(数组+链表+红黑树)
 * 使用key的hashcode和equals作为重复依据
 */
public class HashMapTest {
    public static void main(String[] args) {

        //创建集合
        HashMap<Student,String> studentHashMap = new HashMap<>();

        //1.添加元素
        Student s1 = new Student("孙悟空",01);
        Student s2 = new Student("金蝉子",02);
        Student s3 = new Student("猪八戒",03);
        Student s4 = new Student("沙悟净",04);

        studentHashMap.put(s1,"北京");
        studentHashMap.put(s2,"南京");
        studentHashMap.put(s3,"东京");
        studentHashMap.put(s4,"西京");
        //studentHashMap.put(s4,"中京");//添加失败,西京被中京覆盖
        studentHashMap.put(new Student("沙悟净",04),"西湖");//可以添加成功
                                                  //从写hashcode与equals方法就会添加失败

        System.out.println(studentHashMap.size());
        System.out.println(studentHashMap.toString());

        //2.删除
        studentHashMap.remove(s3);
        System.out.println(studentHashMap.size());
        System.out.println(studentHashMap.toString());

        //3.遍历
        //使用keySet
        System.out.println("================");
        Set<Student> students = studentHashMap.keySet();
        for (Student student : students) {
            System.out.println(student+":"+studentHashMap.get(student));
        }

        //使用entrySet
        System.out.println("================");
        Set<Map.Entry<Student, String>> entries = studentHashMap.entrySet();
        for (Map.Entry<Student, String> entry : entries) {
            System.out.println(entry.getKey()+"="+entry.getValue());
        }

        //判断
        System.out.println(studentHashMap.containsKey(s1));
        System.out.println(studentHashMap.containsKey(new Student("张三", 21)));
        System.out.println(studentHashMap.containsValue("北京"));


    }
}



运行结果

5
{Student{name='孙悟空', stuNo=1}=北京, Student{name='猪八戒', stuNo=3}=东京, Student{name='沙悟净', stuNo=4}=西湖, Student{name='金蝉子', stuNo=2}=南京, Student{name='沙悟净', stuNo=4}=西京}
4
{Student{name='孙悟空', stuNo=1}=北京, Student{name='沙悟净', stuNo=4}=西湖, Student{name='金蝉子', stuNo=2}=南京, Student{name='沙悟净', stuNo=4}=西京}
================
Student{name='孙悟空', stuNo=1}:北京
Student{name='沙悟净', stuNo=4}:西湖
Student{name='金蝉子', stuNo=2}:南京
Student{name='沙悟净', stuNo=4}:西京
================
Student{name='孙悟空', stuNo=1}=北京
Student{name='沙悟净', stuNo=4}=西湖
Student{name='金蝉子', stuNo=2}=南京
Student{name='沙悟净', stuNo=4}=西京
true
false
true



2.3 Map实现类->TreeMap

  • TreeMap:

    • 实现了SortedMap接口(是Map的子接口),可以对key自动排序
  • 特点:唯一、有序(按照升序或降序)

  • 原理:二叉树,key遵循二叉树的特点,放入集合的key的数据对应的类型内部一定要实现比较器(内部比较器与外部比较器,二选一)

2.31 TreeMap的使用实现Comparable接口代码演示

package collection.demo04;

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

    public Student() {
    }

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

    public String getName() {
        return name;
    }

    public int getStuNo() {
        return stuNo;
    }

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

    public void setStuNo(int stuNo) {
        this.stuNo = stuNo;
    }



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

    @Override
    public int compareTo(Student o) {
        /*
        int num1 = this.name.compareTo(o.name);
        int num2 = this.stuNo - o.stuNo;
        return num2 == 0 ? num1 : num2;
        */
        int n1=this.stuNo-o.getStuNo();
        return n1;

    }
}



package collection.demo04;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * TreeMap的使用
 * 存储结构:红黑树
 * 需要有比较规则实现Comparable接口
 */
public class TreeMapTest {
    public static void main(String[] args) {

        //新建集合
        TreeMap<Student,String> treeMap = new TreeMap<>();
        //1.添加元素
        Student s1 = new Student("孙悟空",01);
        Student s2 = new Student("金蝉子",02);
        Student s3 = new Student("猪八戒",03);
        Student s4 = new Student("沙悟净",04);


        treeMap.put(s1,"北京");
        treeMap.put(s2,"上海");
        treeMap.put(s3,"广东");
        treeMap.put(s4,"深圳");

        System.out.println(treeMap.size());
        System.out.println(treeMap.toString());//Exception in thread "main" java.lang.ClassCastException:
                                           //由于是红黑树,需要有比较规则,实现comparable接口

        //删除
        //treeMap.remove(s1);
        treeMap.remove(new Student("沙悟净",04));
        System.out.println(treeMap.size());
        System.out.println(treeMap.toString());


        //3.遍历
        //使用keySet
        System.out.println("================");
        Set<Student> students = treeMap.keySet();
        for (Student student : students) {
            System.out.println(student+":"+treeMap.get(student));
        }

        //使用entrySet
        System.out.println("================");
        Set<Map.Entry<Student, String>> entries = treeMap.entrySet();
        for (Map.Entry<Student, String> entry : entries) {
            System.out.println(entry.getKey()+"="+entry.getValue());
        }

        //判断
        System.out.println(treeMap.containsKey(s1));
        System.out.println(treeMap.containsKey(new Student("张三", 21)));
        System.out.println(treeMap.containsValue("北京"));


    }
}



运行结果

4
{Student{name='孙悟空', stuNo=1}=北京, Student{name='金蝉子', stuNo=2}=上海, Student{name='猪八戒', stuNo=3}=广东, Student{name='沙悟净', stuNo=4}=深圳}
3
{Student{name='孙悟空', stuNo=1}=北京, Student{name='金蝉子', stuNo=2}=上海, Student{name='猪八戒', stuNo=3}=广东}
================
Student{name='孙悟空', stuNo=1}:北京
Student{name='金蝉子', stuNo=2}:上海
Student{name='猪八戒', stuNo=3}:广东
================
Student{name='孙悟空', stuNo=1}=北京
Student{name='金蝉子', stuNo=2}=上海
Student{name='猪八戒', stuNo=3}=广东
true
false
true



2.32 TreeMap的使用匿名内部类实现comparator实现定制比较代码演示


package collection.demo04;

import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * TreeMap的使用
 * comparator 实现定制比较
 */
public class TreeMapTest2 {
    public static void main(String[] args) {
        //新建集合
        TreeMap<Student,String> treeMap = new TreeMap<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int num1 = o1.getName().compareTo(o2.getName());
                int num2 = o1.getStuNo() - o2.getStuNo();
                return num2 == 0 ? num1 : num2;


            }
        });
        //1.添加元素
        Student s1 = new Student("孙悟空",01);
        Student s2 = new Student("金蝉子",02);
        Student s3 = new Student("猪八戒",03);
        Student s4 = new Student("沙悟净",04);


        treeMap.put(s1,"北京");
        treeMap.put(s2,"上海");
        treeMap.put(s3,"广东");
        treeMap.put(s4,"深圳");

        System.out.println(treeMap.size());
        System.out.println(treeMap.toString());//Exception in thread "main" java.lang.ClassCastException:
        //由于是红黑树,需要有比较规则,实现comparable接口

        //删除
        //treeMap.remove(s1);
        treeMap.remove(new Student("沙悟净",04));
        System.out.println(treeMap.size());
        System.out.println(treeMap.toString());


        //3.遍历
        //使用keySet
        System.out.println("================");
        Set<Student> students = treeMap.keySet();
        for (Student student : students) {
            System.out.println(student+":"+treeMap.get(student));
        }

        //使用entrySet
        System.out.println("================");
        Set<Map.Entry<Student, String>> entries = treeMap.entrySet();
        for (Map.Entry<Student, String> entry : entries) {
            System.out.println(entry.getKey()+"="+entry.getValue());
        }

        //判断
        System.out.println(treeMap.containsKey(s1));
        System.out.println(treeMap.containsKey(new Student("张三", 21)));
        System.out.println(treeMap.containsValue("北京"));


    }
}



运行结果

4
{Student{name='孙悟空', stuNo=1}=北京, Student{name='金蝉子', stuNo=2}=上海, Student{name='猪八戒', stuNo=3}=广东, Student{name='沙悟净', stuNo=4}=深圳}
3
{Student{name='孙悟空', stuNo=1}=北京, Student{name='金蝉子', stuNo=2}=上海, Student{name='猪八戒', stuNo=3}=广东}
================
Student{name='孙悟空', stuNo=1}:北京
Student{name='金蝉子', stuNo=2}:上海
Student{name='猪八戒', stuNo=3}:广东
================
Student{name='孙悟空', stuNo=1}=北京
Student{name='金蝉子', stuNo=2}=上海
Student{name='猪八戒', stuNo=3}=广东
true
false
true


3.Collection工具类与Properties集合

3.1.Collection工具类

  • 概念:集合工具类,定义了除了存取以外的集合常用方法。

  • 方法:copy复制、reverse反转、shuffle打乱、sort排序

    • 反转集合中元素的顺序:public static void reverse(List<?> list)
    • 随机重置集合元素的顺序:public static void shuffle(List<?> list)
    • 升序排序(元素类型必须实现Comparable接口):public static void sort(List<T> list)

3.11 Colletion工具类的使用代码演示:

package collection.demo04;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
 * Colletion工具类的使用
 */
public class CollectionsTest {
    public static void main(String[] args) {

        ArrayList<Integer> arrayList = new ArrayList<>();
        arrayList.add(12);
        arrayList.add(54);
        arrayList.add(108);
        arrayList.add(36);
        arrayList.add(72);
        arrayList.add(5);

        // sort 排序
        System.out.println("排序之前"+arrayList.toString());
        Collections.sort(arrayList);
        System.out.println("排序之后  " +arrayList.toString());

        // binarySearch 二分查找
        int i = Collections.binarySearch(arrayList,12);
        System.out.println(i);// 存在返回下标
        int i1 = Collections.binarySearch(arrayList, 102);
        System.out.println(i1);// 没有返回负数

        // copy 复制
        ArrayList<Integer> arrayList1 = new ArrayList<>();
        //*需要注意的是 dest 和 list 大小必须一致 才能复制成功
        for (int i2 = 0; i2 < arrayList.size(); i2++) {
            arrayList1.add(0);
        }
        Collections.copy(arrayList1,arrayList);
        System.out.println(arrayList1.toString());

        // reverse 反转
        System.out.println("反转之前  " +arrayList.toString());
        Collections.reverse(arrayList);
        System.out.println("反转之后  " +arrayList.toString());

        // shuffle 打乱
        Collections.shuffle(arrayList);
        System.out.println("打乱之后  " + arrayList.toString());

        //补充:list集合 转成数组
        Integer[] integers = arrayList.toArray(new Integer[2]);
        System.out.println(integers.toString());

        //补充: 数组转成集合
        String[] arr={"张三","李四","王二","麻子","赵六"};
        List<String> strings = Arrays.asList(arr);
        System.out.println(strings.toString());

        // 集合是一个受限集合,不能添加和删除,因为数组长度固定
        //strings.add("钱七");//java.lang.UnsupportedOperationException
        //strings.remove(0);


        // 基本类型数组转集合时,需要变成包装类
        int[] arr1={1,5,7,8,15,24};
        List<int[]> ints = Arrays.asList(arr1);
        System.out.println("被认为数组对象,仅一个元素  "+ints);

        Integer[] arr2={3,6,9,18,36};
        List<Integer> integers1 = Arrays.asList(arr2);
        System.out.println("基本类型包装类多个对象  " + integers1);


    }
}

运行结果

排序之前[12, 54, 108, 36, 72, 5]
排序之后  [5, 12, 36, 54, 72, 108]
1
-6
[5, 12, 36, 54, 72, 108]
反转之前  [5, 12, 36, 54, 72, 108]
反转之后  [108, 72, 54, 36, 12, 5]
打乱之后  [36, 108, 54, 12, 5, 72]
[Ljava.lang.Integer;@1540e19d
[张三, 李四, 王二, 麻子, 赵六]
被认为数组对象,仅一个元素  [[I@677327b6]
基本类型包装类多个对象  [3, 6, 9, 18, 36]


3.2 Properties集合

  • Properties:属性集合,Hashtable的子类,要求Key和Value都是String。通常用于配置文件的读取

  • 特点:

    • 1.存储属性名和属性值

    • 2.属性名和属性值都是字符串类型

    • 3.没有泛型

    • 4.和流有关


3.21 集合properties的使用代码演示:

package collection.demo04;

import java.io.*;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/**
 * 演示集合properties的使用
 *  Properties文件操作
 *  properties可以用来做配置文件
 *  * javaweb javaee开发中通常会用到
 */
public class PropertiesTest {
    public static void main(String[] args) throws IOException {

        Properties properties = new Properties();
        //添加数据
        properties.setProperty("username","zhangsan");
        properties.setProperty("age","20");
        properties.setProperty("sex","man");
        properties.setProperty("Nationality","Chinese");

        System.out.println(properties.toString());


        //遍历
        //3.1 keySet
        System.out.println("--------------------------------");
        Set<Object> objects = properties.keySet();
        for (Object object : objects) {
            System.out.println(object+"---"+properties.getProperty((String) object));
        }

        //3.2 entrySet

        System.out.println("--------------------------------");
        Set<Map.Entry<Object, Object>> entries = properties.entrySet();
        for (Map.Entry<Object, Object> entry : entries) {
            System.out.println(entry.getKey()+":"+entry.getValue());
        }

        //3.3 stringPropertyNames()
        System.out.println("--------------------------------");
        Set<String> strings = properties.stringPropertyNames();//返回键集
        for (String string : strings) {
            System.out.println(string+"=="+properties.getProperty(string));
        }

        //和流有关的方法
        //list:将属性列表输出到指定的输出流
        PrintWriter printWriter = new PrintWriter("D:\\printing.txt");
        properties.list(printWriter);
        printWriter.close();
        System.out.println("list方法完成");


        //store保存:将此Properties表中的属性列表(键和元素对)写入输出流
        FileOutputStream fileOutputStream = new FileOutputStream("D:\\Store.properties");
        properties.store(fileOutputStream,"注释");
        fileOutputStream.close();
        System.out.println("store方法完成");

        //load加载:从输入流中读取属性列表(键和元素对)
        Properties properties1 = new Properties();
        FileInputStream fileInputStream = new FileInputStream("D:\\Store.properties");
        properties1.load(fileInputStream);
        System.out.println(properties1.toString());
        System.out.println("load方法完成");


    }
}

运行结果

{age=20, sex=man, Nationality=Chinese, username=zhangsan}
--------------------------------
age---20
sex---man
Nationality---Chinese
username---zhangsan
--------------------------------
age:20
sex:man
Nationality:Chinese
username:zhangsan
--------------------------------
age==20
sex==man
username==zhangsan
Nationality==Chinese
list方法完成
store方法完成
{age=20, sex=man, username=zhangsan, Nationality=Chinese}
load方法完成

tt


ee



更多参考

千峰教育-集合框架详解

posted @ 2022-07-23 17:55  哼哼哈¥  阅读(58)  评论(0编辑  收藏  举报