Java——Map集合里的HashMap,LinkedHashMap,TreeMap类的学习与实现案例

本文深入讲解Java中的Map集合,包括其基本概念、功能方法、遍历方式及HashMap、LinkedHashMap、TreeMap的具体应用。通过实例演示了如何进行键值对的增删查改操作,以及Map集合在实际编程中的灵活运用。

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

通过前面学习Set集合,在理解Map集合时也变得十分容易。

Map集合:是一个双列集合 Map<K,V>,k代表的是键,v代表的是值,是一个接口,方法都是抽象的,不能被实例化,将键映射到值的对象。一个映射不能包含重复键,每个键最多只能映射到一个值
     Set底层依赖的是Map,Map集合不能直接迭代
     
     Map集合的功能:
         1.1.添加功能
             V put(K key,V value):添加元素
                 如果键是第一次存储,就直接存储元素,返回null;如果键不是第一次存在,就用值把以前的值替换掉,返回以前的值
         1.2.删除功能
             void clear():移除所有的键值对元素
             V remove(Object key):根据键删除键值对元素,并把值返回
         1.3.判断功能
             boolean containsKey(Object key):判断集合是否包含指定的键
             boolean containsValue(Object value):判断集合是否包含指定的值
             boolean isEmpty():判断集合是否为空
         1.4.获取功能
             Set<Map.Entry<K,V>> entrySet():
             V get(Object key):根据键获取值
             Set<K> keySet():获取集合中所有键的集合
             Collection<V> values():获取集合中所有值的集合
         1.5.长度功能
             int size():返回集合中键值对的个数
     
     Map集合的遍历:
         1.通过键取找值
         2.通过键值对对象去找键和值
         
     实现HashMap集合键是Student值是String的例子
     
     LinkedHashMap的使用:底层是链表实现的,可以保证怎么存就怎么取
     
     实现TreeMap集合键是Student值是String的例子

 

package pra_13;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class J_26 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//1.1
		Map<String,Integer> map=new HashMap<>();//不能实例化,只能通过父类引用指向子类对象
		Integer i1=map.put("aa", 11);
		Integer i2=map.put("bb", 22);
		Integer i3=map.put("cc", 33);
		Integer i4=map.put("aa", 55);
		System.out.println(map);	//{aa=55, bb=22, cc=33}
		System.out.println(i1);		//null
		System.out.println(i2);		//null
		System.out.println(i3);		//null
		System.out.println(i4);		//11	相同的键不存储,将被覆盖的值返回
		
		//1.2
		Integer i5=map.remove("bb");	//根据键删除元素,返回value
		System.out.println(map); 	//{aa=55, cc=33}
		System.out.println(i5); 	//22
		
		//1.3
		System.out.println(map.containsKey("aa"));  	//true
		System.out.println(map.containsValue(55));	 	//true
		
		//1.4
		Collection<Integer> c=map.values();
		System.out.println(c); 				//[55, 33]
		
		//1.5
		System.out.println(map.size()); 	//2
		
		//Map集合的遍历:1.
		Integer i6=map.get("aa");		//根据键获取值
		System.out.println(i6);			//55
		
		Set<String> keySet=map.keySet();	//获取所有键的集合
		Iterator<String> it=keySet.iterator();	//获取迭代器
		while(it.hasNext()){		//判断集合是否有元素
			String key=it.next();	//获取每一个键
			Integer value=map.get(key);
			System.out.println(key+":"+value); //aa:55 cc:33
			
		}
		//用增强for循环也一样
		for (String string : map.keySet()) {	//map.keySet()是所有键的集合
			System.out.println(string+":"+map.get(string));
		}
		
		//2.第二种迭代:通过键值对对象找键和值
		//Map.Entry说明Entry是Map的内部接口,将键和值封装成了Entry对象,并存储在Set集合中
		Set<Map.Entry<String, Integer>> entry=map.entrySet();
		//获取每一个对象
		Iterator<Map.Entry<String, Integer>> it2=entry.iterator();
		while(it2.hasNext()){
			//获取每个Entry对象
			Map.Entry<String, Integer> en=it2.next();	//父类引用指向子类对象
			//Entry<String, Integer> en=it2.next();		直接获取的是子类对象
			String key2=en.getKey();		//根据键值对对象获取键
			Integer value2=en.getValue();	//根据键值对对象获取值
			System.out.println(key2+".."+value2);
		}
		
		//建议使用
		for (Map.Entry<String, Integer> entry2 : map.entrySet()) {
			System.out.println(entry2.getKey()+"....."+entry2.getValue());
		}
		
		//实现HashMap集合键是Student值是String的例子
		HashMap<People8,String> hm=new HashMap<>();
		hm.put(new People8("aa",11), "zxc");
		hm.put(new People8("bb",22), "bnm");
		hm.put(new People8("aa",11), "qwe");
		hm.put(new People8("dd",44), "rty");
		System.out.println(hm); 
		
		//LinkedHashMap的使用
		LinkedHashMap<People8,String> lhm=new LinkedHashMap<>();
		lhm.put(new People8("aa",11), "zxc");
		lhm.put(new People8("bb",22), "bnm");
		lhm.put(new People8("aa",11), "qwe");
		lhm.put(new People8("dd",44), "rty");
		System.out.println(lhm); 
		
		//实现TreeMap集合键是Student值是String的例子
		TreeMap<People8,String> tm=new TreeMap<>();	//需要重写Comparable接口的compareTo抽象方法
		tm.put(new People8("aa",11), "zxc");
		tm.put(new People8("bb",22), "bnm");
		tm.put(new People8("aa",11), "qwe");
		tm.put(new People8("dd",44), "rty");
		System.out.println(tm);
		
			//比较器比较
		TreeMap<People8,String> tm2=new TreeMap<>(new Comparator<People8>(){

			@Override
			public int compare(People8 o1, People8 o2) {
				int num=o1.getName().compareTo(o2.getName());
				return num==0? o1.getAge()-o2.getAge(): num;
			}
			
		});	 
		tm2.put(new People8("aa",11), "zxc");
		tm2.put(new People8("bb",22), "bnm");
		tm2.put(new People8("aa",11), "qwe");
		tm2.put(new People8("dd",44), "rty2");
		System.out.println(tm2);


		//统计字符串中每个字符出现的次数
		String str="assdvsdcdscxcxczdadasds";
		char[] arr=str.toCharArray();
		HashMap<Character,Integer> hm=new HashMap<>();
		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()) {
			System.out.println(key+"..."+hm.get(key));
		}
		//HashMap嵌套HashMap
		HashMap<People8,String> hm9=new HashMap<>();
		hm9.put(new People8("aa",11), "zxc");
		hm9.put(new People8("bb",22), "bnm");
		hm9.put(new People8("dd",44), "rty2");
		
		HashMap<People8,String> hm10=new HashMap<>();
		hm10.put(new People8("ee",11), "iop");
		hm10.put(new People8("gg",22), "jkl");
		hm10.put(new People8("jj",44), "mpl");
		
		HashMap<HashMap<People8,String>,String> hm7=new HashMap<>();
		hm7.put(hm9, "1");
		hm7.put(hm10, "2");
		for (HashMap<People8,String> h : hm7.keySet()) {
			String value=hm7.get(h);
			for (People8 key : h.keySet()) {
				String value2=h.get(key);
				System.out.println(key+"..."+value2+"..."+value);
			}
		}
		//Collections工具类的一些功能实现
		ArrayList<String> list=new ArrayList<>();
		list.add("a");
		list.add("d");
		list.add("c");
		list.add("b");
		Collections.sort(list);
		System.out.println(list); 	//[a, b, c, d]
		System.out.println(Collections.binarySearch(list, "d")); 	//3
		System.out.println(Collections.max(list)); 	//d
		System.out.println(Collections.min(list)); 	//a
		Collections.reverse(list);
		System.out.println(list); 	//[d, c, b, a]
		Collections.shuffle(list);
		System.out.println(list); 	//[a, b, d, c]
	}
}
class People8 implements Comparable<People8>{
	private String name;
	private int age;
	public People8() {
		super();	
	}
	public People8(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;
	}
	public String toString() {
		return "People [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;
		People8 other = (People8) 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;
	}
	@Override
	public int compareTo(People8 o) {
		int num=this.age-o.age;
		return num==0? this.name.compareTo(o.name): num;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值