Java中的Set集合和Map集合

Set集合

在这里插入图片描述
其底层 HashMap 实例的默认初始容量是 16,加载因子是 0.75。

HashSet如何保证存入的元素唯一性?

​ 存入的元素必须重写hashcod()和equals()方法,Integet和String类型已重写这两种方法,其他类型的不重写就保证不了唯一性,通过冲重写hashcode()方法是为了将元素放在对应的位置上,减少比较次数,这样保证了高效,但是这样还会出现相同的哈希值,我们就需要去重写eauals()方法比较,值不同就会放到不同的位置,来确保唯一性。

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

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
public class MyTest2 {
    public static void main(String[] args) {
        Student s1 = new Student("杜兰特", 29);
        Student s2 = new Student("杜兰特", 29);
        Student s3 = new Student("杜兰特1", 29);
        Student s4= new Student("杜兰特2", 39);
        Student s5 = new Student("杜兰特3", 29);
        HashSet<Student> hashSet = new HashSet<>();
        hashSet.add(s1);
        hashSet.add(s2);
        hashSet.add(s3);
        hashSet.add(s4);
        hashSet.add(s5);
        for (Student student : hashSet) {
            System.out.println(student.getName()+"==="+student.getAge());
        }
    }
}
输出结果:
杜兰特===29
杜兰特2===39
杜兰特3===29
杜兰特1===29

TreeSet实现两种排序的方式

TreeSet 底层数据结构是二叉树,元素唯一,他最大的特点是能够对元素进行排序

1.自然排序

public class MyTest2 {
    public static void main(String[] args) {
        TreeSet<Integer> integers = new TreeSet<>();
        integers.add(23);
        integers.add(25);
        integers.add(13);
        integers.add(27);
        integers.add(34);
        for (Integer integer : integers) {
            System.out.println(integer);
        }
    }
}
输出结果:13 23 25 27 34 

Integer和String类型已经重写了compareTo()方法,String类型排序比较的是它在Ascaii表中的值,如果存入其他类型的,就必须重写compareTo()方法,不重写就会报错,比如说按学生的年龄来排序

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

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

    @Override
    public int compareTo(Student s1) {
        int num=this.age-s1.getAge();
        int num2=num==0?this.name.compareTo(s1.getName()):num;
        return num2;
    }
}
public class MyTest2 {
    public static void main(String[] args) {
        Student s1 = new Student("张三", 20);
        Student s2 = new Student("张三", 21);
        Student s3 = new Student("李四", 20);
        Student s4 = new Student("王五", 23);
        Student s5 = new Student("赵六", 27);
        TreeSet<Student> treeSet = new TreeSet<>();
        treeSet.add(s1);
        treeSet.add(s2);
        treeSet.add(s3);
        treeSet.add(s4);
        treeSet.add(s5);
        for (Student student : treeSet) {
            System.out.println(student.getName()+"=="+student.getAge());
        }
    }
}

2.比较器排序

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

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
public class MyTest2 {
    public static void main(String[] args) {
        Student s1 = new Student("张三", 20);
        Student s2 = new Student("张三", 21);
        Student s3 = new Student("李四", 20);
        Student s4 = new Student("王五", 23);
        Student s5 = new Student("赵六", 27);
        TreeSet<Student> treeSet = new TreeSet<>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                int num=s1.getAge()-s2.getAge();
                int num2=num==0?s1.getName().compareTo(s1.getName()):num;
                return num2;
            }
        });
        treeSet.add(s1);
        treeSet.add(s2);
        treeSet.add(s3);
        treeSet.add(s4);
        treeSet.add(s5);
        for (Student student : treeSet) {
            System.out.println(student.getName()+"=="+student.getAge());
        }
    }
}

Map集合

在这里插入图片描述

基于哈希表的 Map 接口的实现。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。

HashMap集合的两种遍历方式
1,获取所有键存入Set集合,遍历取出键,通过get()方法键找值

public class MyTest3 {
    public static void main(String[] args) {
        HashMap<Integer, String> hashMap = new HashMap<>();
        hashMap.put(1,"我");
        hashMap.put(2,"喜");
        hashMap.put(3,"欢");
        hashMap.put(4,"你");
        Set<Integer> set = hashMap.keySet();
        for (Integer integer : set) {
            System.out.println(integer+"="+hashMap.get(integer));
        }
    }
}

2.获取键值对集合(entry集合),遍历键值对集合,通过Entry提供的getKey()和getValue()获取键和值

public class MyTest3 {
    public static void main(String[] args) {
        HashMap<Integer, String> hashMap = new HashMap<>();
        hashMap.put(1,"我");
        hashMap.put(2,"喜");
        hashMap.put(3,"欢");
        hashMap.put(4,"你");
        Set<Map.Entry<Integer, String>> entries = hashMap.entrySet();
        for (Map.Entry<Integer, String> entry : entries) {
            Integer key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key+"  "+value);
        }
    }
}

应用案例

:案例演示: 需求:统计字符串中每个字符出现的次数
“aababcabcdabcde”,获取字符串中每一个字母出现的次数要求结果:a(5)b(4)c(3)d(2)e(1)

public class MyTest3 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一段字符串");
        String s = sc.nextLine();
        HashMap<Character, Integer> hashMap = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {

            char c = s.charAt(i);
            if (!hashMap.containsKey(c)){
                hashMap.put(c,1);
            }else {
                Integer integer = hashMap.get(c);
                integer++;
                hashMap.put(c,integer);
            }
        }
        Set<Map.Entry<Character, Integer>> entries = hashMap.entrySet();
        for (Map.Entry<Character, Integer> entry : entries) {
            System.out.println(entry.getKey()+"("+entry.getValue()+")");
        }

    }
}

A:案例演示
集合嵌套之HashMap嵌套HashMap

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

public class MyTest3 {
    public static void main(String[] args) {
//        基础班
//        张三      20
//        李四      22
//        就业班
//        王五      21
//        赵六      23
        HashMap<String, Integer> hashMap = new HashMap<>();
        hashMap.put("张三",20);
        hashMap.put("李四",22);
        HashMap<String, Integer> hashMap1 = new HashMap<>();
        hashMap1.put("王五",21);
        hashMap1.put("赵六",23);
        HashMap<String, HashMap<String, Integer>> hashMap2 = new HashMap<>();
        hashMap2.put("基础班",hashMap);
        hashMap2.put("就业班",hashMap1);
        Set<Map.Entry<String, HashMap<String, Integer>>> entries = hashMap2.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>> set = value.entrySet();
            for (Map.Entry<String, Integer> integerEntry : set) {
                Integer value1 = integerEntry.getValue();
                String key1 = integerEntry.getKey();
                System.out.println(key1+"    "+value1);
            }
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值