Java之map

总结

Map 用于保存具有映射关系的数据:相对于字典

  1. 因此 Map 集合里保存着两组值,一组值用于保存 Map 里的 Key,另外一组用于保存 Map 里的 Value
  2. Map 中的 key 和 value 都可以是任何引用类型的数据
  3. Map 中的 Key 不允许重复,即同一个 Map 对象的任何两个 Key 通过 equals 方法比较中返回 false
  4. Key 和 Value 之间存在单向一对一关系,即通过指定的 Key 总能找到唯一的,确定的 Value。

HashMap方法

public class Test02 {
	public static void main(String[] args) {
		//创建map集合
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("a",11);
		map.put("c",13);
		map.put("b", 9);
		System.out.println(map);//{a=11, b=9, c=13}
		
		//通过key获取value的值
		map.get("a");
		System.out.println(map.get("a"));//11
		
		//判断集合中是否包含指定key
		map.containsKey("b");
		System.out.println(map.containsKey("b"));
		
		//判断集合中是否包含指定value
		map.containsValue(11);
		System.out.println(map.containsValue(11));
		
		//集合长度
		map.size();
		System.out.println(map.size());
		
		Set<String> keys = map.keySet();//获取map中的key的集合
		map.values();//获取map中value的集合
		System.out.println(keys);
		System.out.println(map.values());
		
		//通过keySet遍历map集合
		for(String key: keys) {
			System.out.println("key="+key+",valus="+map.get(key));
		}
		//通过map.entrySet遍历map集合
		Set<Entry<String, Integer>> entry = map.entrySet();
		for(Entry<String, Integer> en : entry) {
			System.out.println("key="+en.getKey()+",valus="+en.getValue());
		}
		/**
		 * TreeMap 存储 Key-Value 对时,需要根据 Key 对 key-value 对进行排序。TreeMap 可以保证所有的 Key-Value 对处于有序状态
		 */
		
		//TreeMap自然排序是纯字典排序
		Map<String, Integer> map1 = new TreeMap<String, Integer>();
		map1.put("c",11);
		map1.put("a",12);
		map1.put("b",22);
		map1.put("ab",44);
		System.out.println(map1);//{a=12, ab=44, b=22, c=11}
				
	}
}

TreeMap方法

  1. TreeMap 存储 Key-Value 对时,需要根据 Key 对 key-value 对进行排序。
  2. TreeMap 可以保证所有的 Key-Value 对处于有序状态
  3. 自然排序:TreeMap 的所有的 Key 必须实现 Comparable 接口,而且所有的 Key 应该是同一个类的对象,否则将会抛出 ClasssCastException
		//TreeMap自然排序是纯字典排序
		Map<String, Integer> map1 = new TreeMap<String, Integer>();
		map1.put("c",11);
		map1.put("a",12);
		map1.put("b",22);
		map1.put("ab",44);
		System.out.println(map1);//{a=12, ab=44, b=22, c=11}
原文地址:https://www.cnblogs.com/istart/p/12019936.html