6_Map集合


Map
|--Hashtable:底层是哈希表数据结构,不可以存入null键,null值。该集合是线程同步的,jdk1.0,效率低。
|--HashMap:底层是哈希表数据结构,允许使用null键和null值,该集合不是线程同步的。jdk1.2,效率高
|--TreeMap:底层是二叉树数据结构。线程不同步,可以用于给map集合中的键进行排序。

和set集合很像。

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

1,添加。

put(k key,v value),如果出现添加时,相同的键。那么后添加的值会覆盖原有键对应的值,并返回被覆盖的值

putAll(Map<? extends K,? extends V>m)

2,删除

clear()

remove(Object key)

3,判断

containsValue(Object value)

containsKey(Object key)

isEmpty()

4,获取

get(Object key)

size()

values()


Set<Map.Entry<K,V>> entrySet():将map集合中的映射关系存入到了set集合中,而这个关系集合类型就是Map.Entry


Set<K>  keySet():将map中所有的键存入到set集合。因为set具备迭代器。

所有可以迭代方式取出所有的键。再根据get方法。获取每一个键对应的值


Map类的演示:

package Map_test;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class MapTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Map<Student,String> hm=new HashMap<Student,String>();
		
		//添加元素
		hm.put(new Student("lisi1",21), "beijing");
		hm.put(new Student("lisi2",22), "shanghai");
		//有重复的键,会调用键的hashCode,和equals方法,如果键相同,就用新值覆盖老值
		hm.put(new Student("lisi2",22), "tianjian");
		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();
		while(it.hasNext())
		{
			Student stu=it.next();
			String str=hm.get(stu);
			System.out.println(stu+"..."+str);
		}
		
		//用 entrySet()方法取出
		Set<Map.Entry<Student,String>> entrySet=hm.entrySet();
		Iterator<Map.Entry<Student,String>> it1=entrySet.iterator();
		
		while(it1.hasNext())
		{
			Map.Entry<Student, String> m=it1.next();
			Student s=m.getKey();
			String st=m.getValue();
			System.out.println(s+"----"+st);
		}
	}

}

class Student implements Comparable<Student>
{
	private String name;
	private int age;
	public Student(String name, int age) {
		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 boolean equals(Object obj) {
		// TODO Auto-generated method stub
		if(!(obj instanceof Student))
			throw new ClassCastException("对象不是Student类型");
		Student stu=(Student)obj;
		
		return this.name.equals(stu.getName())&&this.age==stu.getAge();
	}
	@Override
	public int hashCode() {
		// TODO Auto-generated method stub
		return this.name.hashCode()+this.age*13;
	}
	@Override
	public int compareTo(Student o) {
		// TODO Auto-generated method stub
		
		int num=new Integer(this.getAge()).compareTo(new Integer(o.getAge()));
		if(num==0){
			return this.name.compareTo(o.getName());
		}
		return num;
	}
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return this.name+":"+this.age;
	}
	
	
}

TreeMap演示,还是利用上面的Student类
package Map_test;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;


public class MapTest2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//默认利用Student里面的比较器,按照年龄排序
		TreeMap<Student,String> tm=new TreeMap<Student,String>();
		
		//用自己定义的比较器,按照姓名进行排序
//		TreeMap<Student,String> tm=new TreeMap<Student,String>(new stuNamecomp());
		
		
		tm.put(new Student("lisi02",24),"chongqing");
		tm.put(new Student("lisi01",23),"shanghai");
		tm.put(new Student("lisi04",21),"beijing");
		tm.put(new Student("lisi03",22),"nanjing");
		
		//取出元素
		Set<Map.Entry<Student,String>> entrySet=tm.entrySet();
		Iterator<Map.Entry<Student, String>> it=entrySet.iterator();
		while(it.hasNext())
		{
			Map.Entry<Student,String> map=it.next();
			Student stu=map.getKey();
			String str=map.getValue();
			System.out.println(stu+"..."+str);
		}
	}

}
//自己写个比较器,按照名字来排序
class stuNamecomp implements Comparator<Student>
{

	@Override
	public int compare(Student arg0, Student arg1) {
		// TODO Auto-generated method stub
		int num=arg0.getName().compareTo(arg1.getName());
		if(num==0){
			return new Integer(arg0.getAge()).compareTo(arg1.getAge());
		}
		return num;
	}

	
}


map集合的一个小应用:统计字母出现的次数

思路:

1.将字符串转换成字符数组,因为对每一个字母进行排序。

2.定义一个map集合,因为打印结果的字母有序,所以使用TreeMap集合(character类的默认比较器)

3.遍历字符数组

将每一个字母作为键去查map集合。如果返回null,将该字母和1存入到map集合。如果返回不是null,说明该字母在map集合已经存在并有对应次数。那么就获取该次数并进行自增,然后将该字母自增后的次数存入到map集合中,覆盖掉原来的值。

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class MapTest3 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(charCount("aaab_=+ddddfff"));
		
	}
	
	public static String charCount(String str){
		char []chs=str.toCharArray();
		
		TreeMap<Character,Integer> tm=new TreeMap<Character,Integer>();
		
		//定义计数变量
		int count;
		for(int x=0;x<chs.length;x++){
			//只判断字母出现的次数
			if(!(chs[x]>='a'&&chs[x]<='z'||chs[x]>='A'&&chs[x]<='Z'))
					continue;
			count=0;
			Integer value=tm.get(chs[x]);
			/*if(value==null){
				tm.put(chs[x], 1);
			}
			else{
				value=value+1;
				tm.put(chs[x], value);
			}*/
			
			if(value!=null){
				count=value;
				
			}
			count++;
			tm.put(chs[x], count);
		}
		
		//定义容器类
		StringBuilder sb=new StringBuilder();
		
		//迭代集合中的元素,并将其放到StringBuilder中,形如:a(2)
		Set<Map.Entry<Character,Integer>> entrySet=tm.entrySet();
		Iterator<Map.Entry<Character,Integer>> it=entrySet.iterator();
		
		while(it.hasNext())
		{
			Map.Entry<Character,Integer> map=it.next();
			sb.append(map.getKey()+"("+map.getValue()+") ");
		
		
		}
		
		return sb.toString();
	}

}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值