map集合的知识

本文深入讲解了Java集合框架中的Collections工具类使用方法,包括排序、查找、反转等操作,同时详细解析了Map接口及其实现类HashMap、TreeMap的特性与应用,涵盖了自然排序、比较器排序、嵌套Map和List等高级主题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

							## 集合的知识点

一、Collections
Collections是针对集合进行操作的工具类,collections中的方法都是静态方法
1.1 Collection与Collection的区别
Collection是集合的顶层接口,Collections是针对集合进行操作的工具类,简而言之,Collection是接口,
Collections是对集合进行操作的类
1.2 Collections中的方法
public static void sort(List list):排序,默认情况下是自然排序
public static int binarySearch(Collection c, T key):二分查找法
public static max(Collection<?> coll):最大值
public static void reverse(List<?> list):反转
public static void shuffle(List<?> list):随机置换
例1:

	package com.Collections;
	import java.util.ArrayList;
	import java.util.Collections;
	public class CollectionsDemo {
	public static void main(String[] args) {
	// TODO Auto-generated method stub
	ArrayList<Integer> list=new ArrayList<>();
			list.add(10);
			list.add(5);
			list.add(50);
			list.add(60);
			list.add(2);
	System.out.println(list);
	int binarySearch = Collections.binarySearch(list, 5);	//返回当前元素的索引值
	System.out.println(binarySearch);
	
	Collections.sort(list);//	排序
	
	Collections.reverse(list);	//反转
	System.out.println(list);
	
	Collections.shuffle(list);	//置换
	System.out.println(list);
	Integer max = Collections.max(list);
	System.out.println(max);//求集合的最大值
	
	Integer min= Collections.max(list);
	System.out.println(min);	//	求集合的最小值
	
}

}

1.3 collections中的自定义排序
(1)自然排序
通过实现Comparable,重写compareTo()方法,实现自定义排序

(2)比较排序
通过比较器comparator匿名的形式,实现对集合的排序
例2:

	   package com.Collections2;
		public class Student implements Comparable<Student> {	//实现comparable接口,并重写compareTo方法
		private String name;
		private int age;
		public Student() {
			super();
		}
		public Student(String name, int age) {
			super();
			this.name = name;
			this.age = 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;
		}
		@Override
		public String toString() {
			return "Student [name=" + name + ", age=" + age + "]";
		}
		@Override
		public int compareTo(Student o) {		//重写compareto方法
			// TODO Auto-generated method stub
			return this.age-o.age;
		}
		
	}

测试类

	package com.Collections2;
	import java.util.ArrayList;
	import java.util.Collections;
	import java.util.Comparator;
	
	public class CollectionsDemo {
	
		public static void main(String[] args) {
			// TODO Auto-generated method stub
			ArrayList<Student> list=new ArrayList<>();
			list.add(new Student("爷爷",70));
			list.add(new Student("孙子",10));
			list.add(new Student("爹",90));
			list.add(new Student("娘",50));
			System.out.println(list);
			Collections.sort(list);	//对集合进行排序,通过实现comparable接口,可以对集合进行自定义排序
			System.out.println(list);
		
		Collections.sort(list,new Comparator<Student>() {	//比较器,通过匿名对象new Comparator实现对集合排序				   
	
				@Override
				public int compare(Student o1, Student o2) {
					// TODO Auto-generated method stub
					return o1.getAge()-o2.getAge();
					
				}
			});
			System.out.println(list);
		}
	
	}

二、map

map称为字典
Map的特点:
将键映射到值的对象,一个映射不能包含重复的键,每个键最多只能映射到一个值
例如: a1 >> 我
a2 >> 你 这时候a1映射的值是错的,因为a1键只能映射一个值,但是可以用其他键映射重复的值
a1 >>我

Map集合和Collection的区别:
(1)Map集合存储的元素是成对出现的,Map的集合的键是唯一的,值是可以重复。
(2)Collection集合存储元素的单独出现的,Collection的儿子Set是唯一的,List是可以重复的

注意:
Map集合的从数据结构是针对键有效,跟值无关。
HashMap,TreeMap
Collection集合的数据结构是针对元素有效

Map的功能概述:
添加功能:

	V put(K key, V value):添加元素  

如果键是第一次存储,直接存储该元素,返回是null.
如果键不是第一次存储,就是用值把以前的值进行替换,返回的是以前的值

	System.out.println(map.put("刘恺威", "杨幂"));	//添加的时候,输出的为空
	System.out.println(map);
	System.out.println(map.put("刘恺威", "王鸥")); //当再次对这个键添加时,会返回被替换的值

删除功能:

	void clear():移除所有的键值对元素
   V	remove(Object key):根据键删除键值元素,并把值进行返回

判断功能:

	boolean containsKey(Object key):判断集合是否包含指定的键
	boolean containsValue(Object value):判断集合是否包含指定的值
		  例如:
		 			 boolean containsKey = map.containsKey("邓超");
						System.out.println(containsKey);
							boolean containsValue = map.containsValue("姚笛");
							System.out.println(containsValue);
		      boolean isEmpty():判断集合是否为空	

获取功能:

	  V get(Object key):根据键来获取值
	 Set<K> keySet():获取集合中所有的键
	 例如:
 		Set<String> keySet = map.keySet();	
				for (String string2 : keySet) {	//遍历map
					System.out.println(string2+"--------"+map.get(string2));	//输出每一个键值
				}
   	Collection<V> values():获取集合中所有值的集合
 				Collection<String> values = map.values();
				System.out.println(values);
   	Set<Map.Entry<K,V>> entrySet():返回的是键值对 对象 的集合
 			Set<Map.Entry<String, String>> entrySet = map.entrySet();
					for (Entry<String, String> entry : entrySet) {
				System.out.println(entry.getKey()+"-------"+entry.getValue()); //获得键和键所对应的值
			}

长度功能:

	int size():返回集合中的键值对的对数

2.1 HashMap

HashMap是map的接口实现类
例3: 下面的例子是通过HashMap实现添加键值,然后通过keySe和entrySet两种方式对
集合进行遍历

	ackage com.hwua.Map;
	import java.util.HashMap;
	import java.util.Map.Entry;
	import java.util.Set;
	public class HashMapDemo1 {
	
	public static void main(String[] args) {
	// TODO Auto-generated method stub
	HashMap<Integer, String> map = new HashMap<>();
	//下面的写法是八进制的,但是不能出现8以上的单个数据
	map.put(3, "马克");
	map.put(6, "孙尚香");
	map.put(10, "明世隐");
	map.put(1, "狄仁杰");
	map.put(11, "狄仁杰");			//这一部分是对每一个集合对象进行添加键值
	map.put(12, "明世隐");
	map.put(16, "孙尚香");
	map.put(100, "明世隐");
	System.out.println(map);
	//需求:用不同的方式将键和值进行遍历  格式: 键---值
	Set<Integer> keySet = map.keySet();		//keySet是获取集合中所有的键		
	for (Integer integer : keySet) {					//遍历集合,获得每一个键						
	System.out.println(integer+"----"+map.get(integer));	//输出interger,也就是键,输出map.get(integer)是键所映射的值
	}
	//这一部分是通过keySet实现对集合的遍历
	System.out.println("--------");
	Set<Entry<Integer, String>> entrySet = map.entrySet();	//返回的是键值对的对象 的集合
	for (Entry<Integer, String> entry : entrySet) {					//遍历集合,获得键值			
	System.out.println(entry.getKey()+"----"+entry.getValue());		//输出键以及对应的值
//这一部分是通过	entrySet实现对集合的遍历	
	}
	}
	
	}

例4:
HashMap中键传入引用类,当要比较相等时,要实现HashCode和equals方法,equals方法中要比较
什么就留什么
如:
package com.hwua.Map;

	public class Worker {
	
	private String name;
	private int age;
	public Worker() {
			super();
	}
	public Worker(String name, int age) {
	super();
	this.name = name;
	this.age = 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;
	}
	@Override
	public String toString() {
	return "Worker [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) {			//当要比较什么就留什么,不比较的,需要hashCode()和equals()中实现形式
	if (this == obj)
	return true;
	if (obj == null)
	return false;
	if (getClass() != obj.getClass())
	return false;
	Worker other = (Worker) 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;
			}
	}

实现类
package com.hwua.Map;
import java.util.HashMap;
import java.util.Set;
public class HashMapDemo2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		HashMap<Worker, Integer> map = new HashMap<>();
		map.put(new Worker("张三", 16), 8800);
		map.put(new Worker("李四", 26), 1800);
		map.put(new Worker("王五", 36), 4800);
		map.put(new Worker("张三", 46), 2800);
		map.put(new Worker("张三", 16), 1800);
		
		System.out.println(map);
		
		Set<Worker> keySet = map.keySet();
		for (Worker worker : keySet) {	
			System.out.println(worker+"--"+map.get(worker));  	// map.get(worker是输出每一个键所映射的值
//这部分是遍历集合,输出键以及键所对应的值
		}	
	}
	}

例5:
LinkedHashMap是通过Hash确定集合的唯一性、Linked确定集合的有序性(即存储时进出的顺序一样)
如:

	package com.LinkedHashDemo;
	import java.util.LinkedHashMap;
	public class LinkedHashDemo {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		LinkedHashMap<String, Integer> list=new LinkedHashMap<>();	//	LinkedHashMap的作用在于确保集合的唯一、有序性
		list.put("孔子", 18);
		list.put("老子", 20);
		list.put("儿子", 8);
		list.put("孙子", 50);
		list.put("儿子", 8);	//当再添加这个键时,LinkedHashMap就会限制添加
		list.put("老子", 20);
		System.out.println(list);
	}
	
}

例6:
在集合中嵌套map
如:

	package com.hwua.Map;
	import java.util.ArrayList;
	import java.util.HashMap;
	import java.util.Map.Entry;
	import java.util.Set;
	
	public class ArrayListIncludeHashMapDemo {	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ArrayList<HashMap<String, String>> arrayList = new ArrayList<>();	//相当于sanguo中人物对应关系存放到数组中
		HashMap<String, String> sanguo = new HashMap<>();		//创建sanguo集合,用于存放人物及其值
		sanguo.put("周瑜", "小乔");			//添加人物及值,HashMap中put是添加的意思
		sanguo.put("吕布", "貂蝉");
		arrayList.add(sanguo);	//将人物集合添加到sanguo数组中
		
		HashMap<String, String> xiyouji = new HashMap<>();
		xiyouji.put("牛魔王", "铁扇公主");
		xiyouji.put("至尊宝", "紫霞仙子");
		arrayList.add(xiyouji);
		
		HashMap<String, String> wuxia = new HashMap<>();
		wuxia.put("郭靖", "黄蓉");
		wuxia.put("杨过", "大雕");
		arrayList.add(wuxia);
		
		System.out.println(arrayList);
		for (HashMap<String, String> hashMap : arrayList) {		//遍历数组中存放的是什么种类的集合,如遍历sanguo,xiyouji
			Set<Entry<String, String>> entrySet = hashMap.entrySet();	//返回的是键值对的对象 的集合
			for (Entry<String, String> entry : entrySet) {		//遍历集合中的各个键
				System.out.println(entry.getKey()+"--"+entry.getValue());	//输出键以及键所映射的值
			}
		}
		
	}
	
	}

2.2 TreeMap

		TreeMap:是基于红黑树的Map接口的实现
		例7:
	
	package com.TreeMapDemo;
	import java.util.TreeMap;
	
	public class TreeMapDemo {
	
	public static void main(String[] args) {
	// TODO Auto-generated method stub
	TreeMap<String, String> map=new TreeMap<>();
		map.put("鲁班七号", "鲁班");
		map.put("寒冰射手", "艾射");
		map.put("瞎子", "李青");
		map.put("提莫队长", "提莫");
		map.put("齐天大圣", "孙悟空");
	System.out.println(map);
	}
	
	}

2.2.1TreeMap同样存在comparable接口以及comparator比较器

		1.comparable<T>
				在类中必须实现comparable<T>,重写其comparableTo方法
				
		2. comparator
				比较器comparator,通过匿名对象调用,重写compare
		例8:
	package com.TreeMapDemo2;
	public class Student {
	private String name;
	private int age;
	public Student() {
		super();
	}
	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(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}
	
	}

测试类

	package com.TreeMapDemo2;
	import java.util.Comparator;
	import java.util.TreeMap;
	public class TreeMapDemo {
		public static void main(String[] args) {
			// TODO Auto-generated method stub
		TreeMap<Student, Integer> map = new TreeMap<>(new Comparator<Student>() {  //创建Comparator比较器,
			@Override
		public int compare(Student o1, Student o2) {
		// TODO Auto-generated method stub
			
			int num=o1.getAge()-o2.getAge();		//前面减后面的是从小到大,反之从大到小
			int num1=num==0?o1.getName().compareTo(o2.getName()):num;
			return num1;
		}
	});
	map.put(new Student("张三", 16), 8800);
	map.put(new Student("李四", 26), 1800);
	map.put(new Student("王五", 36), 4800);
	map.put(new Student("张三", 46), 2800);
	map.put(new Student("张三", 16), 1800);
	
	System.out.println(map);
	
	}
	
	}

2.2.2 HashMap嵌套哈希HashMap

		HashMap集合中嵌套map,实际是调用外部集合和内部集合的功能,实现多样的功能
	例9:
	package com.hwua.map;
	import java.util.HashMap;
	import java.util.Map.Entry;
	import java.util.Set;
	
	public class HashMapDemo2 {
	
		public static void main(String[] args) {
			// TODO Auto-generated method stub
			HashMap<String, HashMap<String,Integer>> map = new HashMap<>();	//在游戏中添加职业
			
			HashMap<String, Integer> mm1 = new HashMap<>();	//在职业集合中添加英雄
			
			mm1.put("刘备", 500);
			mm1.put("程咬金", 200);
			mm1.put("吕布", 500);
			map.put("战士", mm1);	//把职业添加到游戏中
		
			
			HashMap<String, Integer> mm2 = new HashMap<>();
			mm2.put("狄仁杰", 350);
			mm2.put("公孙离", 150);
			map.put("射手", mm2);
			System.out.println(map);
			
			HashMap<String, Integer> mm3 = new HashMap<>();
			mm3.put("高渐离", 150);
			mm3.put("诸葛亮",200);
			map.put("法师", mm3);
			System.out.println(map);
			//如何遍历呢?
			Set<String> keySet = map.keySet();	//获得集合的各个键,即获得游戏
			for (String string : keySet) {			//遍历键
				HashMap<String, Integer> hashMap = map.get(string);	// 获得键所映射的值,即获得职业
				Set<String> keySet2 = hashMap.keySet();		//获得集合的各个键,即获得游戏的键
				for (String string2 : keySet2) {		//遍历职业的键
					System.out.println("姓名:"+string2+",基础攻击力:"+hashMap.get(string2));	//	获得键以及对应的映射值,即获得游戏的角色跟属性
				} 
			}
			System.out.println("---------");
			Set<Entry<String, HashMap<String, Integer>>> entrySet = map.entrySet();		//返回的是键值对 对象 的集合,即
			for (Entry<String, HashMap<String, Integer>> entry : entrySet) {			//遍历集合的键
				HashMap<String, Integer> value = entry.getValue();							//获得集合所映射的值
				 Set<Entry<String, Integer>> entrySet2 = value.entrySet();				//返回的是键值对 对象 的集合,即
				 for (Entry<String, Integer> entry2 : entrySet2) {									//遍历集合的键
					 System.out.println(entry2.getKey()+","+entry2.getValue());			//输出键及键所映射的值
				}
			}
			
		}
	
	}

例10:HashMap中嵌套ArrayList
假设HashMap的集合元素是ArrayListr,有3个
每个ArrayList集合的值都是字符串。

	 public class HashMapIncludeArrayListDemo {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		HashMap<String, ArrayList<String>> map = new HashMap<>();
		
		ArrayList<String> list1 = new ArrayList<>();
		ArrayList<String> list2 = new ArrayList<>();
		ArrayList<String> list3 = new ArrayList<>();
		
		list1.add("刘备");
		list1.add("关羽");
		list1.add("张飞");
		map.put("三国", list1);
		
		
		Set<Entry<String, ArrayList<String>>> entrySet = map.entrySet();	//返回的是键值对 对象 的集合
		for (Entry<String, ArrayList<String>> entry : entrySet) {		//遍历键
			System.out.println(entry.getKey());									//打印键
			ArrayList<String> value = entry.getValue();					//获得键所映射的每一个键
			for (String string : value) {												//遍历数组
				System.out.println(string);											//输出数组的各个元素
			}
			System.out.println("---");
		}
	}
	
	}

例11:
1.HashTabel和HashMap的区别:
Hashtable线程安全,效率低,不许null键和null值
HashMap线程不安全,效率高,允许null键和null值,也就是说除了HashMap之外所有的集合都不允许为null值

2.List,Set,Map等接口是否都继承了子Map接口
List,Set不是继承Map接口,他们是继承于Collection接口
Map接口本身就是一个顶层接口

三、总结

1.map是集合接口,其实现类是HashSet、TreeSet等
2.map的添加功能是put,而不是add
3.HashMap和TreeSet的遍历方式为keySet()、entreSet();
4.TreeSet中自然排序comparable跟比较器排序comparator

comparable要实现compare()接口,重写compareTo方法

comparator通过匿名对象调用,重写compare方法

  1. HashMap中键传入引用类,当要比较相等时,要实现HashCode和equals方法,equals方法中要比较
    什么就留什么
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值