集合框架Map,HashMap,TreeMap【JAVA基础】

集合框架Map的所有子类

-----Map集合共性方法

1.添加
put(K key,V value)
//添加元素,如果出现添加时,相同的键,后者覆盖前者,put方法会返回被覆盖的键
putAll(Map<? extends K,? extends V> m)
2.删除
clear()
remove(Object key)
3.判断
containsValue(Object key)
containsKey(Object key)
isEmpty()
4.获取
get(Object key)/可以用get方法的返回的值判断一个键是否存在,通过返回null判断
size()
values()//获取map集合中所有的值
5.两种取出map集合的方式 :
1.keySet():返回map集合的所有键的Set集合,Set
//先获取map集合的所有键的Set集合,keySet();
Set keySet=map.keySet();
//有了Set集合,就可以获取其迭代器
Iterator it=keySet.iterator();
while(it.hasNext()) {
String key=it.next();
//有了键可以通过map集合的get方法获取其对应的值
String value=map.get(key);
System.out.println(“key:”+key+" value:"+value);
}

2.entrySet():返回map集合中的映射关系的Set集合,Set<Map.Entry<k,v>>
//将Map集合中的映射关系取出,存入到Set集合中。
Set<Map.Entry<String, String>> entrySet=map.entrySet();
Iterator<Map.Entry<String, String>> it2=entrySet.iterator();
while(it2.hasNext()) {
Map.Entry<String, String> me=it2.next();
System.out.println(me.getKey()+","+me.getValue());
}
//Map.Entry 其实Entry也是一个接口,它是Map结构中的一个内部接口

Set底层就是使用了Map集合

|–map

Map集合:该集合存储键值对,一对一往里存,而且要保证键的唯一性。
key:键 value:值

|–HashTable

|–HashTable:底层是哈希表数据结构,不可以存入null键null值,该集合是同步的 JDK1.0 效率低

|–HashMap

|–HashMap:底层是哈希表数据结构,允许使用null键null值,该集合是非同步的。JDK1.2 效率高

案例:

package 黑马集合框架Map;

import java.util.*;
/*
每一个学生都有对应的归属地
学生Student,地址String
学生属性:姓名,年龄。
注意:姓名和年龄相同的视为同一个学生。
保证学生的唯一性

1.描述学生
2.定义map容器,将学生作为键,地址作为值,存入。
3.获取map集合中的元素
*/
public class MapTest {
	public static void main(String[] args) {
		HashMap<Student,String> hm=new HashMap<Student,String>();
		hm.put(new Student("lisi1",21), "beijing");
		hm.put(new Student("lisi1",21), "tianjing");
		hm.put(new Student("lisi2",22), "shanghai");
		hm.put(new Student("lisi3",23), "nanjing");
		hm.put(new Student("lisi4",24), "wuhan");
		
		//第一种取出方式 keySet
//		Set<Student> keySet=hm.keySet();
//		Iterator<Student> it=keySet.iterator();
		Iterator<Student> it=hm.keySet().iterator();
		while(it.hasNext()){
			Student key=it.next();
			String Value=hm.get(key);//根据键获取值
			System.out.println("key:"+key+"   Value:"+Value);			
		}
		
		//第二种取出方式 entrrySet
		Set<Map.Entry<Student, String>> entrySet=hm.entrySet();
		Iterator<Map.Entry<Student, String>> iter=entrySet.iterator();
		while(iter.hasNext()) {
			Map.Entry<Student, String> me=iter.next();
			Student stu=me.getKey();
			String addr=me.getValue();
			System.out.println(stu+"...."+addr);
		}
		
	}
}
class Student implements Comparable<Student>//让元素具备比较性
{
	private String name;
	private int age;
	Student(String name,int age){
		this.name=name;
		this.age=age;
	}
	public int compareTo(Student s) {//让元素具备比较性
		int num=new Integer(this.age).compareTo(s.age);
		if(num==0)
			return this.name.compareTo(s.name);
		return num;
	}
	/* 
	   TreeSet排序的第一种方式(默认顺序):让元素自身具备比较性
	     实现Comparable接口强制让元素(学生类)具备比较性
	     覆盖接口中的compareTo方法
   */
	
	public int hashCode()
	{
		return name.hashCode()+age*34;
	}
	public boolean equals(Object obj)
	{
		if(!(obj instanceof Student))
			throw new ClassCastException("类型不匹配");
		Student s=(Student)obj;
		return this.name.equals(s.name) && this.age==s.age;
		
	}
	/* 
	   HashSet如何保证元素的唯一性:
	          通过元素的两个方法,hasCode和equals来完成
	          如果元素的HashCode值相同,才会判断equals是否为true
	          如果元素的HashCode值不同,不会调用equals。
	     注意:对于判断元素是否存在,以及删除等操作,依赖的方法是元素的hasCode和equals方法     
	*/
	public String getName() {
		return name;
	}
	public int getAge() {
		return age;
	}
	public String toString()
	{
		return name+":"+age;
	}
}

|–TreeMap

|–TreeMap:底层是二叉树数据结构,线程不同步,可以用于给mao集合中的键进行排序
案例:

package 黑马集合框架Map;

import java.util.*;

/*
练习:
"sdfgzxcvasdfxcvdf"获取该字符串中的字母出现的次数

希望打印结果:a(1)c(2)
通过结果发现,每一个字母都有对应的关系
说明字母和次数之间都有映射关系

注意:当发现有映射关系时,可以选择map集合
因为map集合中存放的就是映射关系

思路:
1.将字符串转换成字符数组,因为要对每一个字母进行操作
2.定义一个map集合,因为打印结果的字母有顺序,所以使用TreeMap集合
3.遍历字符数组
   将每一个字母作为键去查map集合
   如果返回null,将该字母和1存入到map集合中
   如果返回不是null,说明该字母在map集合已经存在并有对应的次数。
   那么就获取该次数并进行自增,然后将该字母和自增后的次数存入到map集合中,覆盖原来键所对应的值
4.将map集合中的数据变成指定的 字符串形式 返回    
 */
public class MapTest3 {

	public static void main(String[] args) {
		String result=countChar("sdfgzxcvasdfxcvdf");
		System.out.println(result);
	}
	public static String countChar(String str1) {
		char[] str=str1.toCharArray();//将字符串转换成字符数组
		TreeMap<Character,Integer> tm=new TreeMap<Character,Integer>();//创建TreeMap		
		int count=0;
		for(int i=0;i<str.length;i++) {//遍历
			Integer value=tm.get(str[i]);//获取次数
			
			if(value!=null)//代码优化
				count=value;
			tm.put(str[i], ++count);
			count=0;
//			if(value==null){//没有该键
//				tm.put(str[i], 1);
//			}
//			else {
//				tm.put(str[i], ++value);//次数++
//			}
		}
		
		//取出存入到字符串缓冲区StringBuffer,最后toString输出字符串
		StringBuffer sb=new StringBuffer();
		Set<Map.Entry<Character, Integer>> entrySet=tm.entrySet();
		Iterator<Map.Entry<Character, Integer>> it=entrySet.iterator();
		while(it.hasNext()) {
			Map.Entry<Character, Integer> me=it.next();
			sb.append(me.getKey()+"("+me.getValue()+")\t");			
		}
		return sb.toString();//返回字符串
	}

}

原创文章 27 获赞 2 访问量 1133

猜你喜欢

转载自blog.csdn.net/liudachu/article/details/105553454