Map集合的简单介绍及使用
Map集合的体系结构:
Map接口的特点:
用于存储任意键值对(Key-Value)。
键:无下标、不可以重复(唯一)。
值:无下标、可以重复 。
(1)HashMap
key为无序的、不可重复,key相等的时候会被后者覆盖。
存储结构是哈希表,线程不安全,运行效率快。
允许用null作为key或是value。
代码示例:
public class Demo01 {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
//添加
//map.put(key,value); key值不可重复,否则会被后者覆盖
map.put("d",1);
map.put("d",4);
map.put("b",2);
map.put("c",3);
map.put("a",5);
//会按照key值排序
System.out.println("初始值:" + map);
//获取 根据key获取value
System.out.println("输出key值为a的value值:" + map.get("a"));
//修改
map.put("a",1);
System.out.println("修改a后:" + map);
//删除
map.remove("c");
System.out.println("删除c后:" + map);
System.out.println("--------keySet遍历---------");
//3.1使用keySet();
for (String key : map.keySet()) {
System.out.println(key+" "+map.get(key));
}
System.out.println("--------entrySet遍历---------");
//3.2使用entrySet();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey()+" "+entry.getValue());
}
System.out.println("--------迭代器遍历1---------");
//把map集合中的key存放到set集合中
Set<String> set = map.keySet();
//遍历set集合
Iterator<String> it = set.iterator();
while(it.hasNext()){
//存放在set集合中的对象是map中的key
String key = it.next();
System.out.println(key+" "+map.get(key));
}
System.out.println("--------迭代器遍历2---------");
//把map中的key-value存放到map的节点中,再把节点存放到set集合中
Set<Map.Entry<String, Integer>> set1 = map.entrySet();
//把set集合中存放的entry对象放在迭代器中
Iterator<Map.Entry<String, Integer>> it1 = set1.iterator();
while(it1.hasNext()){
//迭代器获取的对象为entry对象
Map.Entry<String, Integer> entry = it1.next();
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
}
一个简单需求:HashMap实现相同key存入数据后不被覆盖
(2)TreeMap
底层是红黑树, key的约束与TreeSet存储对象的约束一致。
由于有此底层代码 return t.setValue(value),所以元素不可重复;代表当比较规则返回0,存储的value会覆盖旧的value。
实现了SortedMap接口(Map的子接口),可以对key自动排序,Key需实现Comparable接口。
代码示例:
public class Demo01 {
public static void main(String[] args) {
//新建集合(定制比较)
TreeMap<Student, String> treeMap=new TreeMap<Student,String>();
//1添加元素
Student s1=new Student("孙悟空", 100);
Student s2=new Student("猪八戒", 101);
Student s3=new Student("沙和尚", 102);
treeMap.put(s1, "北京");
treeMap.put(s2, "上海");
treeMap.put(s3, "深圳");
treeMap.put(new Student("沙和尚", 102), "南京");
System.out.println("元素个数:"+treeMap.size());
System.out.println(treeMap.toString());
//2删除
//treeMap.remove(new Student("猪八戒", 101));
//System.out.println(treeMap.size());
//3遍历
for (Student key : treeMap.keySet()) {
System.out.println(key+" "+treeMap.get(key));
}
}
}
class Student implements Comparable<Student>{
private String name;
private int stuNo;
public Student(String name, int stuNo) {
super();
this.name = name;
this.stuNo = stuNo;
}
public int getStuNo() {
return stuNo;
}
@Override
public String toString() {
return name + " " + stuNo;
}
@Override
public int compareTo(Student o) {
int n2=this.stuNo-o.getStuNo();
return n2;
}
}