Map集合是存储键值对的集合,其中,键对象不允许重复,而值对象可以重复常用的有两种即HashMap和TreeMap。
1.TreeMap
TreeMap,是一个能比较元素大小的Map集合,会对传入的key进行了大小排序。其中,可以使用元素的自然顺序,也可以使用集合中自定义的比较器来进行排序。
TreeMap排序是以key值进行排序,排序方式与TreeSet相似。当Key的类型是基本类型时系统会自动进行比较排序,而当Key类型是自定义的数据类型时需要实现Comparable接口,并实现
compareTo()方法依据返回值进行排序
ublic class Student implements Comparable<Student>{
private int age;
private String name;
public Student(int age, String name) {
this.age = age;
this.name = name;
}
public Student() {
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
@Override
public int compareTo(Student o) {
return o.age-this.age;
}
}
public static void main(String[] args) {
TreeMap<Student,Integer> map=new TreeMap<>();
Student s=new Student(18,"张三");
Student s1=new Student(22,"张三");
Student s2=new Student(23,"张三");
map.put(s,11);
map.put(s1,12);
map.put(s2,13);
System.out.println(map.toString());
}
注意实现 Comparable接口时要注意<>中的泛型要写要比较的数据类型。
使用比较器排序也和TreeSet集合类似。
TreeMap具有如下特点:
-
不允许出现重复的key;
-
可以插入null键,null值;
-
可以对元素进行排序;
-
无序集合(插入和遍历顺序不一致)
2.HashMap
同理与TreeMap一样HashMap也需要对键进行排序,不过HashMap是依据Hash值进行排序,因此如果需要把Key值按照指定规则进行排序。需要重写hashCode()方法来计算hash值进行比较。
3.遍历Map集合
遍历map集合共有两种方法,
一种是
1.先使用keySet()将key值全部取出放在set集合
2.遍历key值获得对象
3.使用get(key)方法,获取value值
TreeMap<Student,Integer> map=new TreeMap<>();
Student s=new Student(18,"张三");
Student s1=new Student(22,"张三");
Student s2=new Student(23,"张三");
map.put(s,11);
map.put(s1,12);
map.put(s2,13);
Set<Student> students = map.keySet();
for (Student student : students) {
Integer i = map.get(student);
System.out.println(student+"============="+i);
}
第二种是;
1.先使用entrySet()将map集合中每对键值对都遍历出来
2.遍历entrySet()集合;
3.再对每个entrySet对象使用getKey();getValue();方法获得key和value值
TreeMap<Student,Integer> map=new TreeMap<>();
Student s=new Student(18,"张三");
Student s1=new Student(22,"张三");
Student s2=new Student(23,"张三");
map.put(s,11);
map.put(s1,12);
map.put(s2,13);
Set<Map.Entry<Student, Integer>> entries = map.entrySet();
for (Map.Entry<Student, Integer> entry : entries) {
Student key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key+"============="+value);
}
以上既是对map集合的总结