6.3 HashMap和TreeMap

系列 - JAVA集合

本手册主要内容是 HashMap、LinkedHashMap、TreeMap,包括这三个类的基础操作、遍历和排序。

创建对象 new、添加元素 add、删除元素 remove、判断存在 contains

java

import java.util.HashMap;    
  
public class Example15 {  
    public static void main(String[] args) {  
        HashMap map = new HashMap(); // 创建Map对象  

        map.put("1","张三");  
        map.put("2","李四");          //存储键和值  
        map.put("3","王五");  

		System.out.println("1:" + map.get("1"));  // 根据键获取值
		System.out.println("2:" + map.get("2"));
		System.out.println("3:" + map.get("3"));
		System.out.println("键值对数量:" + map.size());

		// 删除“1:张三”
		map.remove("1");
		

		if (map.containsKey("1")) {
            System.out.println("1号存在");
		} else {
			System.out.println("1号不存在");
		}
		
		if (map.containsValue("李四")) {
		    System.out.println("李四存在");
		} else {
			System. out. println("李四不存在");
		}

		// 删除所有
		map.clear();  
		System.out.println("键值对数量:" + map.size());
    }  
}

方法一:遍历所有的键,通过 .get() 函数拿到对应值

java

Set keySet = map.keySet();      //获取键的集合  
Iterator it = keySet.iterator();//迭代键的集合  
while (it.hasNext()) {  
    Object key = it.next();  
    Object value = map.get(key); //获取每个键所对应的值  
    System.out.println(key + ":" + value);  
}
Caution

需要在文件开头导入 Set 和 Iterator 的包

方法二:获取所有键值对,再分别拿出每一个键和值

java

Set entrySet = map.entrySet();
Iterator it = entrySet.iterator();         // 获取Iterator对象
while (it.hasNext()){
	//获取集合中键值对映射关系
	Map.Entry entry = (Map.Entry) (it.next());
	Object key = entry.getKey();      //获取Entry中的键
	Object value = entry.getValue();  //获取Entry中的值
	System.out.println(key + ":" + value);
}

HashMap 集合迭代出来元素的顺序和存入的顺序是不一致的。

如果想让这两个顺序一致,可以使用 LinkedHashMap 类,它是 HashMap 的子类,与LinkedList一样,它也使用双向链表来维护内部元素的关系,使Map元素迭代的顺序与存入的顺序一致。

java

class Fruit implements Comparable<Fruit> {
    String name;
    double price;
    
    public Fruit(String name, double price) {
        this.name = name;
        this.price = price;
    }
    
    // 按价格从低到高排序
    @Override
    public int compareTo(Fruit other) {
        if(this.price > other.price) return 1;
        if(this.price < other.price) return -1;
        return 0;
    }
    
    public String toString() {
        return name + ":" + price + "元";
    }
}

public class Main {
    public static void main(String[] args) {
        TreeSet<Fruit> fruits = new TreeSet<>();
        fruits.add(new Fruit("苹果", 5.5));
        fruits.add(new Fruit("香蕉", 3.5));
        fruits.add(new Fruit("橙子", 4.5));
        
        // 输出:[香蕉:3.5元, 橙子:4.5元, 苹果:5.5元]
        System.out.println(fruits);
    }
}
  1. 创建一个学生类,包含学号、姓名;
  2. 创建一个 LinkedHashMap 对象,存储三个学生对象,用学号作为,学生对象作为
    1. 其中一个学生用自己的真实信息
  3. 删除学生后遍历(不要删自己)
  1. 修改学生类,增加分数属性(score);
  2. 修改学生类,实现 Comparable 接口和 compareTo 方法;
  3. 创建一个 TreeMap 对象,存储刚刚的三个学生对象;
  4. 遍历,观察结果是否有序

相关内容