JAVA 映射表

Map

映射表是一种依照键/值对存储元素的容器。它提供了通过键快速获取、删除和更新键/值对的功能。映射表将键与值一起保存,键可以是任意类型的对象,映射表中不能有重复的键,如果存储的键在映射表中已经存在则值会覆盖。
Map是映射表的父接口,他的方法有
V put (K key, V value):添加元素。
V get(Object Key) 返回键对应的值
int size() 返回映射表中的条目数
void clear ():移除所有的键值对元素
V remove (Object key):根据键删除键值对元素,并把值返回
boolean containsKey (Object key):判断集合是否包含指定的键
boolean containsValue (Object value):判断集合是否包含指定的值
boolean isEmpty ():判断集合是否为空
Set keySet();//获取键的集合
Collection values();//获取所有值的集合
Set<Map<K,V>> entrySet()返回一个包含了该映射表中的条目的集合。

public class MapDemo {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        //put() 放入元素
        map.put(1,"aaa");
        map.put(2,"ccc");
        map.put(3,"eee");
        //get()返回键对应的值
        System.out.println(map.get(1));//aaa
        //size()
        System.out.println(map.size());//3
        System.out.println(map);//{1=aaa, 2=ccc, 3=eee}
        //remove()移除指定键
        System.out.println(map.remove(2));//ccc
        System.out.println(map);//{1=aaa, 3=eee}
        //clear()删除所有元素
        map.clear();
        System.out.println(map);//{}
        map.put(1,"aaa");
        map.put(2,"aaa");
        map.put(3,"eee");
        System.out.println( map.containsKey(1) );//true
        System.out.println(map.containsValue("ccc"));//true
        // keySet();//获取键的集合
        System.out.println(map.keySet());//[1, 2, 3]
        //  values();//获取所有值的集合
        System.out.println(map.values());//[aaa, aaa, eee]
    }
}

遍历Map的方法
1通过可以通过键找值的方式来遍历
2通过 Map.Entry<K, V> 方法返回的Set集合遍历

public class MapDemo {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1,"aaa");
        map.put(2,"aaa");
        map.put(3,"eee");
        map.put(4,"fff");
        map.put(5,"iii");
        //1通过可以通过键找值的方式来遍历
        Set<Integer> k = map.keySet();
        for (int key:k) {
            String v = map.get(key);
            System.out.println(key+" "+v);
        }
        //2通过 Map.Entry<K, V> 方法返回的Set集合遍历
        Set<Map.Entry<Integer, String>> entries = map.entrySet();
        for (Map.Entry<Integer, String> entry : entries) {
            System.out.println(entry.getKey()+" "+entry.getValue());
        }
    }
}

Map接口下有三个具体的类实现了Map接口,分别是HashMap、LinkedHashMap、TreeMap。
演示使用Map存储自定义的类

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

HashMap

HashMap与HashSet相同,底层都是通过哈希表来实现的。都是通过重写hashCode()与equals()方法来确保元素的唯一性。
而HashSet的底层其实也是使用了HashMap。

public class MapDemo {
    public static void main(String[] args) {
        //存储键是 String 值是Student
        HashMap<String, Student> hashMap = new HashMap<>();
        hashMap.put("s001",new Student("钟楚红",23));
        hashMap.put("s002", new Student("梅艳芳", 27));
        hashMap.put("s003", new Student("李丽珍", 26));
        hashMap.put("s004", new Student("翁虹", 27));
        hashMap.put("s005", new Student("叶子楣", 29));
        hashMap.put("s005", new Student("叶子楣222", 29));
        //遍历
        for (String s : hashMap.keySet()) {
            Student student = hashMap.get(s);
            System.out.println(s+"=="+student.getName()+"=="+student.getAge());
        }
    }
}

LinkedHashMap

LinkedHashMap在HashMap的基础上实现了元素的有序性。
LinkedHashMap与LinkedHashSet相同,都是通过链表来实现元素的有序性。

public class LinkedHashMapDemo {
    public static void main(String[] args) {
       // LinkedHashMap 元素有序,且唯一
        LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
        map.put(100, "abc");
        map.put(200, "ccc");
        map.put(300, "ddd");
        Set<Map.Entry<Integer, String>> entries = map.entrySet();
        for (Map.Entry<Integer, String> entry : entries) {
            Integer key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key+"==="+value);
        }
    }
}

TreeSet

TreeSet底层的数据结构是二叉树,与TreeSet相同可以通过自然排序(实现comparable接口重写compareTo()方法)或者比较排序(通过构造函数添加比较器—重写Comparator接口的compare方法)。
自然排序

public class TreeMapDemo {
    public static void main(String[] args) {
        TreeMap<Student, Integer> map = new TreeMap<>();
        map.put(new Student("钟楚红", 23), 10);
        map.put(new Student("梅艳芳", 27), 9);
        map.put(new Student("李丽珍", 26), 1);
        map.put(new Student("翁虹", 27), 4);
        map.put(new Student("叶子楣", 29), 2);
        map.put(new Student("叶子楣222", 29), 3);
        System.out.println(map);
    }
}

//其中重写Student的compareTo方法按照年龄排序
public int compareTo(Student s) {
        int num=this.getAge()-s.getAge();
        int num2=num==0?this.name.compareTo(s.name):num;
        return num2;
    }

选择排序

public class TreeMapDemo2 {
    public static void main(String[] args) {
        //按照姓名排序
        TreeMap<Student, Integer> map = new TreeMap<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int num=o1.getName().compareTo(o2.getName());
                int num2=num==0?o1.getAge()-o2.getAge():num;
                return num2;
            }
        });
        map.put(new Student("钟楚红", 23), 10);
        map.put(new Student("梅艳芳", 27), 9);
        map.put(new Student("李丽珍", 26), 1);
        map.put(new Student("翁虹", 27), 4);
        map.put(new Student("叶子楣", 29), 2);
        map.put(new Student("叶子楣222", 29), 3);
        System.out.println(map);
    }
}

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值