JAVA基础——Map集合,Map集合特点,根据键找值,寻找键和值,HashMap,TreeMap,LinkedHashMap的基本功能,hashtable与hashMap区别

一、 Map集合概述和特点

  1. Map接口概述
  • 将键映射到值的对象
  • 一个映射不能包含重复的键
  • 每个键最多只能映射到一个值
  1. Map接口和Collection接口的不同
  • Map是双列的,Collection是单列的
  • Map的键唯一,Collection的子体系Set是唯一的
  • Map集合的数据结构(TreeMap,hashMap)值针对键有效,跟值无关;Collection集合的数据结构是针对元素有效

二、 Map集合的功能概述

1. 添加功能

  • V put(K key,V value):添加元素。
  • 如果键是第一次存储,就直接存储元素,返回null
  • 如果键不是第一次存在,就用值把以前的值替换掉,返回以前的值
Map<String, Integer> map =new HashMap<String, Integer>();
		//put的返回值是根据后面的值的类型相同
		Integer i1= map.put("张三", 13);
		Integer i2= map.put("李四", 15);
		Integer i3= map.put("王五", 14);
		Integer i4= map.put("赵六", 16);
		Integer i5= map.put("张三", 16);	
//因为map集合种相同的键不存储,值覆盖,把被覆盖的值返回
		System.out.println(map);
		System.out.println(i1);
		System.out.println(i2);
		System.out.println(i3);
		System.out.println(i4);
		System.out.println(i5);

效果如下:
在这里插入图片描述
2. 删除功能

  • void clear():移除所有的键值对元素
  • V remove(Object key):根据键删除键值对元素,并把值返回
Map<String, Integer> map =new HashMap<String, Integer>();
		map.put("张三", 13);
		map.put("李四", 15);
		map.put("王五", 14);
		map.put("赵六", 16);
		//根据键删除元素,返回键对应的值
		Integer value =map.remove("张三");
		System.out.println(value);
		System.out.println(map);

效果如下:
在这里插入图片描述

3. 判断功能

  • boolean containsKey(Object key):判断集合是否包含指定的键
  • boolean containsValue(Object value):判断集合是否包含指定的值
  • boolean isEmpty():判断集合是否为空
		System.out.println(map.containsKey("张三"));
		System.out.println(map.containsValue(100));

返回值 一个true。一个false

4. 获取功能

  • Set<Map.Entry<K,V>> entrySet():
  • V get(Object key):根据键获取值
  • Set<K> keySet():获取集合中所有键的集合
  • Collection<V> values():获取集合中所有值的集合

前三个看后面的遍历。这里介绍最后一个

Map<String, Integer> map =new HashMap<String, Integer>();
		map.put("张三", 13);
		map.put("李四", 15);
		map.put("王五", 14);
		map.put("赵六", 16);
		
		Collection<Integer>collection =map.values();
		System.out.println(collection);

效果如下:
在这里插入图片描述

5. 长度功能

  • int size():返回集合中的键值对的个数
System.out.println(map.size());

三、 Map集合的遍历之键找值

主要介绍map的获取功能
键找值思路:

  • 获取所有键的集合
  • 遍历键的集合,获取到每一个键
  • 根据键找值

方式一:使用迭代器遍历,

Map<String, Integer> map =new HashMap<String, Integer>();
		map.put("张三", 13);
		map.put("李四", 15);
		map.put("王五", 14);
		map.put("赵六", 16);
		
		Integer i =map.get("张三");		//根据键获取值
		System.out.println(i);
		
		Set<String> keySet =map.keySet();	//获取所有键的集合
		Iterator<String> it =keySet.iterator();//获取迭代器
		while (it.hasNext()) {
    
    					
		//判断集合中是否有元素
			String key = (String) it.next();	//获取每一个键
			Integer value =map.get(key);		//根据键获取值
			System.out.println(key+"=="+value);
		}

方式二:foreach循环

Map<String, Integer> map =new HashMap<String, Integer>();
		map.put("张三", 13);
		map.put("李四", 15);
		map.put("王五", 14);
		map.put("赵六", 16);
		 for (String key : map.keySet()) {
    
    		//map.keySet()是所有键的集合
			System.out.println(key+"=="+map.get(key));
		}
	}

效果均相同:
在这里插入图片描述

四、 Map集合的遍历之键值对对象找键和值

键值对对象找键和值思路:

  • 获取所有键值对对象的集合
  • 遍历键值对对象的集合,获取到每一个键值对对象
  • 根据键值对对象找键和值

先解释Map.Entry<K,V>是什么意思

interface Inter{
    
    
	interface Inter2{
    
    
		public void show();
	}
}
//想要实现Inter2接口需要使用Inter.Inter2
class Demo implements Inter.Inter2{
    
    
	@Override
	public void show() {
    
    

	}
}

同理:Entry是map下的一个子接口

方式一:根据迭代器查找

Map<String, Integer> map =new HashMap<String, Integer>();
		map.put("张三", 13);
		map.put("李四", 15);
		map.put("王五", 14);
		map.put("赵六", 16);
		//Map.Entry说明Entry是Map的内部接口,将键和值封装成了Entry对象,并存储在Set集合中
Set<Map.Entry<String, Integer>>entrySet =map.entrySet();
		//获取每一个对象
Iterator<Map.Entry<String, Integer>> it = entrySet.iterator();
		while (it.hasNext()) {
    
    
			//获取每一个Entry对象
		Map.Entry<String, Integer> en =it.next();//父类引用指向子类对象
	// Entry<String ,Integer> en=it.next;	//直接获取的是子类对象。Entry是map.Entry的子接口
	//以上两种方式均可
		String key =en.getKey();			
//根据键值对对象获取键											
		Integer value =en.getValue();		
//根据键值对对象获取值
			System.out.println(key+"==="+value);
		}
	}

方式二:foreach循环遍历

Map<String, Integer> map =new HashMap<String, Integer>();
		map.put("张三", 13);
		map.put("李四", 15);
		map.put("王五", 14);
		map.put("赵六", 16);
		for (Map.Entry<String, Integer> en : map.entrySet()) {
    
    
	System.out.println(en.getKey()+"=="+en.getValue());
		}

效果如下两者均相同:
在这里插入图片描述

五、 HashMap集合键是Student值是String的案例

public class Student {
    
    
	private String name;
	private int 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;
	}
	public Student() {
    
    
		super();
	}
	public Student(String name, int age) {
    
    
		
		this.name = name;
		this.age = age;
	}
	@Override
	public String toString() {
    
    
		return "Student [name=" + name + ", age=" + age + "]";
	}
	@Override
	public int hashCode() {
    
    
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
    
    
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (age != other.age)
			return false;
		if (name == null) {
    
    
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
}

注意该处我们重写了hashCode方法和equals方法。所以当我们的姓名和年龄相同的时候视为同一对象。会对其进行覆盖。

测试类:

		//键表示字符串对象,值代表归属地
		HashMap<Student, String > hm =new HashMap<Student, String>();
		hm.put(new Student("张三",12), "安徽");
		hm.put(new Student("张三",12), "上海");
		hm.put(new Student("王五",11), "广州");
		hm.put(new Student("赵六",14), "深圳");
		
		System.out.println(hm);

效果如下:
在这里插入图片描述

六、 LinkedHashMap的概述和使用

LinkedHashMap的特点
* 底层是链表实现的可以保证怎么存就怎么取

LinkedHashMap<String, Integer> lhm =new LinkedHashMap<String, Integer>();
		lhm.put("张三",13);
		lhm.put("李四",14);
		lhm.put("赵六",12);
		lhm.put("王五",17);
		System.out.println(lhm);

效果如下:
在这里插入图片描述

七、 TreeMap集合键是Student值是String的案例

TreeMap<Student, String> tm =new TreeMap<Student, String>();
		tm.put(new Student("张三", 13),"安徽");
		tm.put(new Student("李四", 12),"安徽");
		tm.put(new Student("王五", 14),"安徽");
		tm.put(new Student("赵六", 15),"安徽");
		
		System.out.println(tm);

此时我们应当重写Comparable接口。我们按照年龄进行排序

@Override
	public int compareTo(Student o) {
    
    
		int num =this.age -o.age;
		
		return num==0? this.name.compareTo(o.name):num;
	}

效果如下:
在这里插入图片描述

如果我们采用调用比较器Compartor

TreeMap<Student, String> tm =new TreeMap<Student, String>(new Comparator<Student>() {
    
    
			@Override
			public int compare(Student s1, Student s2) {
    
    
				int num =s1.getName().compareTo(s2.getName());
				return num ==0?s1.getAge()-s2.getAge():num;
			}
		});
		tm.put(new Student("张三", 13),"安徽");
		tm.put(new Student("李四", 12),"安徽");
		tm.put(new Student("王五", 14),"安徽");
		tm.put(new Student("赵六", 15),"安徽");

效果如下:
在这里插入图片描述

八、 练习比如:aaabbbbcccc。计算a出现次数b出现次数。

分析:

  1. 定义一个需要被统计字符的字符串
  2. 将字符串转换为字符数组
  3. 定义双列集合,存储字符串中字符以及字符出现的次数
  4. 遍历字符数组获取每一个字符并将字符存储在双列集合中
  5. 存储过程中要做判断,如果集合中不包含这个键,就将该字符当作键,值为1存储如果集合中包含这个键,就将值+1存储
  6. 打印双列集合,获取字符出现的次数:统计字符串中每个字符出现的次数
public class Demo1_Test {
    
    
	public static void main(String[] args) {
    
    
		//1,定义一个需要被统计字符的字符串
		String s="aaaabbbbccccc";
		//2.将字符串转换为字符数组
		char[] arr =s.toCharArray();
		//定义双列集合存储字符串中字符以及字符出现的次数。HashMap效率最高
		HashMap<Character, Integer> hm =new HashMap<Character, Integer>();
		//遍历字符数组获取每一个字符,并将字符存储在双列集合中
		for (char c : arr) {
    
    
			//
			//if (!hm.containsKey(c)) {
    
    
			//	hm.put(c, 1);
			//}else {
    
    
			//	hm.put(c,hm.get(c)+1);
			//}
			hm.put(c,!hm.containsKey(c)?1:hm.get(c)+1);
		}
		for (Character key : hm.keySet()) {
    
    
	//hm.keySet代表所有键的集合
			System.out.println(key+"="+hm.get(key));
//根据键获取值
		}
	}

}

九、 集合嵌套之HashMap嵌套HashMap

//定义第一个集合
		HashMap<Student, String> hm1 =new HashMap<Student, String>();
		hm1.put(new Student("张三", 13),"安徽");
		hm1.put(new Student("李四", 15),"浙江");
		hm1.put(new Student("王五", 14),"河南");
		hm1.put(new Student("赵六", 12),"河北");
		
		//定义第二个集合
		HashMap<Student, String> hm2 =new HashMap<Student, String>();
		hm2.put(new Student("戚明辉", 16),"上海");
		hm2.put(new Student("江杰", 19),"北京");
		hm2.put(new Student("虞俊文", 18),"广州");
		hm2.put(new Student("宋进锋", 17),"深圳");
		
		//定义一个总的集合
		HashMap<HashMap<Student, String>, String> hm3 =new HashMap<HashMap<Student,String>, String>();
		hm3.put(hm1, "集合1");
		hm3.put(hm2, "集合2");
		
		//遍历双列集合
		for (HashMap<Student, String> h : hm3.keySet()) {
    
    	//hm3.keySet()代表的是双列集合中键的集合
			String value =hm3.get(h);		//get(h)根据键对象获取值对象
			//遍历键的双列集合对象
			for (Student key : h.keySet()) {
    
    //h.keySet获取集合中所有的学生键对象
				String value2=h.get(key);
				
				System.out.println(key+"=="+value2+"=="+value);
			}
		}

效果如下:
在这里插入图片描述

十、 HashMap和Hashtable的区别

  • Hashtable是JDK1.0版本出现的,是线程安全的,效率低,HashMap是JDK1.2版本出现的,是线程不安全的,效率高
  • Hashtable不可以存储null键和null值,HashMap可以存储null键和null值
    共同点:底层都是哈希算法,都是双列集合
HashMap<String, Integer> hm =new HashMap<String, Integer>();
	hm.put(null, 23);
	hm.put("李四", 24);
	System.out.println(hm);
	
	Hashtable<String, Integer> ht =new Hashtable<String, Integer>();
	ht.put(null, 23);
	ht.put("张三",null);
	System.out.println(ht);

输出效果:map不报错,可以存储null。但是table会报错。

十一、 Collections工具类的概述和常见方法讲解

当一个类中所有的方法都是静态的,那么它会私有自己的构造方法

public static <T> void sort(List<T> list)

自动排序

public static <T> int binarySearch(List<?> list,T key)

二分法查找

public static <T> T max(Collection<?> coll)

获取最大值

public static void reverse(List<?> list)

将集合反转

public static void shuffle(List<?> list)

将集合随机置换。类似于洗牌

案例:

public static void main(String[] args) {
    
    
	demo1();
	demo2();
	demo3();
	demo4();
	demo5();
	}
	public static void demo5() {
    
    
		List<String> list =new ArrayList<String>();
		list.add("a");
		list.add("c");
		list.add("d");
		list.add("f");
		list.add("g");
		System.out.println("-------------");
		System.out.println("demo5测试结果:");
		Collections.shuffle(list);			//随机置换
		System.out.println(list);
	}
	public static void demo4() {
    
    
		List<String> list =new ArrayList<String>();
		list.add("a");
		list.add("c");
		list.add("d");
		list.add("f");
		list.add("g");
		System.out.println("-------------");
		System.out.println("demo4测试结果:");
		Collections.reverse(list);			//反转集合
		System.out.println(list);
	}
	public static void demo3() {
    
    
		List<String> list =new ArrayList<String>();
		list.add("a");
		list.add("c");
		list.add("d");
		list.add("f");
		list.add("g");
		System.out.println("-------------");
		System.out.println("demo3测试结果:");
		System.out.println(Collections.max(list));		//根据默认排序结果获取集合中的最大值
	}
	public static void demo2() {
    
    
		List<String> list =new ArrayList<String>();
		list.add("a");
		list.add("c");
		list.add("d");
		list.add("f");
		list.add("g");
		System.out.println("-------------");
		System.out.println("demo2测试结果:");
		System.out.println(Collections.binarySearch(list, "c"));
		//如果搜索键包含在列表中,则返回搜索键的索引;否则返回(-(插入点)-1)
		System.out.println(Collections.binarySearch(list, "b"));
	}

	public static void demo1() {
    
    
		List<String> list =new ArrayList<String>();
		list.add("c");
		list.add("a");
		list.add("a");
		list.add("b");
		list.add("d");
		Collections.sort(list);			//将集合排序
		System.out.println("-------------");
		System.out.println("demo1测试结果:");
		System.out.println(list);
	}

效果如下:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Mr_GYF/article/details/109036429