Test__Map练习__【TreeMap对象操作】【TreeMap字符串操作】【Map扩展】


练习一:对象操作

定义:每一个学生都有对应的归属地。

学生Student,地址String。
学生属性:姓名,年龄。姓名和年龄相同的视为同一个学生。保证学生的唯一性。
步骤:
1,描述学生。
2,定义map容器。将学生作为键,地址作为值。存入。

3,获取map集合中的元素。

定义一个学生类需要的元素:除了基本的构造函数,私有化的属性,以及公共获取方法法外

如果在集合框架中操作,如要存入hashSet集合:需要覆盖hashCode() 方法和equals()方法;在二叉树(treeSet、treeMap)中操作时则需要具备可比性,继承Comparable接口,实现该接口的方法compareTo()

import java.util.*;
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)//为TreeMap复写compareTo方法
	{
		int n = new Integer(this.age).compareTo(new Integer(s.age));//int数据类型包装成对象调用compareTo()
		if (n ==0)
			return this.name.compareTo(s.name);
		return n;
	}

	public int hashCode()//为hasnSet集合复写hashCode和equals方法
	{
		return name.hashCode()+age*33;
	}
	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;
	}

	public String getName()//获取Student描述的操作
	{
		return name;
	}
	public int getAge()
	{
		return age;
	}
	public String toString()
	{
		return name+":"+age;
	}
}

class MapTest 
{
	public static void sop(Object obj)
	{
		System.out.println(obj);
	}
	public static void main(String[] args) 
	{
		HashMap<Student,String> hm = new HashMap<Student,String>();//map的泛型,键值对应
		hm.put(new Student("haha01",24),"beijing");
		hm.put(new Student("haha03",23),"shanghai");
		hm.put(new Student("haha02",22),"guangzhou");
		hm.put(new Student("haha04",21),"shenzhen");

//keySet取出方式		
		Set<Student> keySet = hm.keySet();
		Iterator<Student> it = keySet.iterator();
		while (it.hasNext())
		{
			Student s = it.next();		//迭代获取Set中Student对象作为Map的键
			String address = hm.get(s);	//通过键s获取对应的值;Map的get(k)方法
			sop(s+" 地址:"+address);
		}
//entrySet取出方式
		Set<Map.Entry<Student,String>> entrySet = hm.entrySet();
		Iterator<Map.Entry<Student,String>> ite = entrySet.iterator();
		while (ite.hasNext())
		{
			Map.Entry<Student,String> me = ite.next();	//迭代获取Set集合中的Map.Entry类型数据
			Student stu = me.getKey();	//通过方法getKey()获取Map.Entry关系中的的Key,即Student
			String address = me.getValue();//获取值,即地址
			sop(stu+" aderss: "+address);
		}
	}
}
TreeMap
需求:对学生对象的年龄进行升序排序。
因为数据是以键值对形式存在的。所以要使用可以排序的Map集合。TreeMap。

import java.util.*;
class StComparator implements Comparator<Student>	//比较器,由Student中实现的compareTo以age比较不同,改为按照name比较
{
	public int compare(Student s1,Student s2)
	{
		int num = s1.getName().compareTo(s2.getName());
		if (num==0)
			return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
		return num;
	}
}
class  MapTest2
{
	public static void main(String[] args) 
	{
		TreeMap<Student,String> tm = new TreeMap<Student,String>(new StComparator());
		tm.put(new Student("haha01",21),"北京");
		tm.put(new Student("aaha02",23),"上海");
		tm.put(new Student("zaha04",22),"南京");
		tm.put(new Student("saha03",25),"杭州");
		tm.put(new Student("saha03",25),"深圳");

		Set<Map.Entry<Student,String>> entrySet = tm.entrySet();
		Iterator<Map.Entry<Student,String>> it = entrySet.iterator();
		while (it.hasNext())
		{
			Map.Entry<Student,String> me = it.next();
			Student s = me.getKey();
			String a = me.getValue();
			System.out.println(s+" : "+a);
		}
	}
}

练习二:字符串操作

获取字符串中的字母出现的次数。打印结果:a(1)c(2).....
分析:
通过结果发现,每一个字母都有对应的次数。说明字母和次数之间都有映射关系。
当数据之间存在这映射关系时,就要先想map集合。因为map集合中存放就是映射关系
思路:
1,将字符串转换成字符数组。因为要对每一个字母进行操作。
2,定义一个map集合,因为打印结果的字母有顺序,所以使用treemap集合。
3,遍历字符数组。
将每一个字母作为键去查map集合。
如果返回null,将该字母和1存入到map集合中。
如果返回不是null,说明该字母在map集合已经存在并有对应次数。
那么就获取该次数并进行自增。,然后将该字母和自增后的次数存入到map集合中。覆盖调用原理键所对应的值。
4,将map集合中的数据变成指定的字符串形式返回。

图示:

代码:

import java.util.*;
class MapTest3 
{
	public static void main(String[] args) 
	{
		String s = charCount("dad,,dfa.*#@.gfsaa");
		System.out.println(s);
	}
	
	public static String charCount(String s)
	{
		char[] chs = s.toCharArray();		//1,将字符串转成字符数组
		TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();//2,定义Map集合,字符为键,次数为值
		for (int x=0; x<chs.length ; x++)	//3,遍历字符数组
		{
			if (!(chs[x]>='a'&&chs[x]<='z')||(chs[x]>='A'&&chs[x]<='Z'))//健壮性判断,只要字母
				continue;				//如果不是字母,则跳过当前继续往下面执行
			Integer value = tm.get(chs[x]);//通过键获取值
			if (value == null)
				value = 1;
			else
				value+=1;
			tm.put(chs[x],value);
		}
		System.out.println(tm);//打印TreeMap
									//4,将map集合中的数据变成指定的字符串形式返回。
		StringBuilder sb = new StringBuilder();
		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();
			Character key = me.getKey();
			Integer value = me.getValue();
			sb.append(key+"("+value+")");
		}
		return sb.toString();
	}
}

运行结果:


三、map集合扩展

map可以多层嵌套,即一个集合可以作为另一个集合的value存在,一对多的关系

import java.util.*;
class  MapDemo3
{
	public static void main(String[] args) 
	{
		//getInfo(a);
		//getInfo(b);
		//method_1();
		method_2();
	}
	public static void method_2()
	{
		HashMap<String,List<Student>> hm = new HashMap<String,List<Student>>();
		List<Student> a = new ArrayList<Student>();				//Map中有List
		List<Student> b = new ArrayList<Student>();
		hm.put("aaaaaa",a);
		hm.put("bbbbbb",b);
		a.add(new Student("02","zhangsa_a"));
		a.add(new Student("04","lisi____a"));
		b.add(new Student("03","wangwu__a"));
		b.add(new Student("01","zhaoliu_a"));

		Iterator<String> it = hm.keySet().iterator();//获取hm的键
		while (it.hasNext())
		{
			String hmab = it.next();
			List<Student> ab = hm.get(hmab);//通过键获取值
			sop(hmab);
			getInfo_2(ab);			//调用,循环嵌套
		}
	}
	public static void getInfo_2(List<Student> list)//遍历获取List的Student对象
	{
		Iterator<Student> it = list.iterator();
		while (it.hasNext())
		{
			Student s = it.next();
			sop(s);
		}
	}

	public static void method_1()
	{
		HashMap<String,HashMap<String,String>> hm = new HashMap<String,HashMap<String,String>>();
		HashMap<String,String> a = new HashMap<String,String>();		//Map中有Map
		HashMap<String,String> b = new HashMap<String,String>();
		
		hm.put("aaa",a);
		hm.put("bbb",b);
		a.put("01","zhangsan_a");
		a.put("02","lisissaa_a");
		b.put("01","wangwu_b");
		b.put("02","hahabb_b");
		
		Iterator<String> it = hm.keySet().iterator();//获取hm的键
		while (it.hasNext())
		{
			String hmab = it.next();
			HashMap<String,String> ab = hm.get(hmab);//通过键获取值
			sop(hmab);
			getInfo_1(ab);			//调用,循环嵌套
		}
	}
	public static void getInfo_1(HashMap<String,String> ab)//获取“子Map”对象
	{
		Iterator<String> it = ab.keySet().iterator();//keySet方法获取
		while (it.hasNext())
		{
			String id = it.next();
			String name = ab.get(id);	//通过key获取value
			sop(id+" : "+name);
		}
	}
	public static void sop(Object obj)
	{
		System.out.println(obj);
	}
}
class Student
{
	private	String id;
	private String name;
	Student(String id,String name)
	{
		this.id = id;
		this.name = name;
	}
	public String toString()
	{
		return id+" : "+name;
	}
}


原文地址:https://www.cnblogs.com/Joure/p/4337219.html