Java的 Map集合特点:
该集合存储键值对,是成对存储的,而且要保证键的唯一性。
1,添加
put(R key,V value)
putAll (Map<? extends,K? extends y>m)
2,删除
clear()
从此映射中移除所有映射关系(可选操作)。
3,判断
containsKey (object key)
如果此映射包含指定键的映射关系,则返回true。
containsValue (Object value)
如果此映射将一个或多个键映射到指定值,则返回true。
isEmpty()
如果此映射未包含键值映射关系,则返回true
4,获取
get(Object key)
返回指定键所映射的值;如果此映射不包含该键的映射关系,则返回null
size ()
返回此映射中的键值映射关系数
values ()
返回此映射中包含的值的Collection视图
entrySet ()
返回此映射中包含的映射关系的Set视图
keySet ()
返回此映射中包含的键的Set视图
Map包含Hashtable HashMap TreeMap
Hashtable:底层是哈希表数据结构,不可以存入null键null值,该集合是线程同步的。 JDK1.0 效率低
HashMap:底层是哈希表数据结构,允许使用null键和null值,该集合是不同步的。 JDK1.2 效率高
TreeMap:底层是二叉树数据结构,线程不同步。可以用于给Map集合中的键进行排序。
Map和Set很像:
其实Set底层就是使用了Map集合
public class Main {
public static void main(String[] args) {
// write your code here
Map<String,String> map=new HashMap<String,String>();
//添加元素,添加元素如果出现添加时相同的键,后添加的值会覆盖原有的值
map.put("01","zero one");
map.put("01","zero 1");
map.put("03","zero three");
map.put(null,"haha");
System.out.println("containsKey:"+map.containsKey("02"));
//System.out.println("remove:"+map.remove("02"));
//可以通过get方法的返回值判断一个键是否存在
System.out.println("get:"+map.get(null));
//获取map集合中的所有值。
Collection<String>coll=map.values();
System.out.println(coll);
System.out.println(map);
}
}
Map集合小练习
每一个学生都有对应的归属地。
学生Student,地址String.
学生属性:姓名,年龄。
注意:姓名和年龄相同的视为同一个学生。
保证学生的唯一性。
1,描述学生。
2,定义map容器。将学生作为键,地址作为值。存入。
3,获取map集合中的元素。
public class Main {
public static void main(String[] args) {
// write your code here
HashMap<Student,String> hm=new HashMap<Student,String>();
//添加元素
hm.put(new Student("zhangsan",18),"beijing");
hm.put(new Student("lisi",19),"nanjing");
hm.put(new Student("wangwu",17),"tianjing");
hm.put(new Student("zhaoliu",20),"wuhan");
hm.put(new Student("zefaer",21),"chengdu");
//第一种取出方式
Set<Student> keySet=hm.keySet();
//获取迭代器
Iterator<Student> it=keySet.iterator();
while (it.hasNext())
{
Student stu=it.next();
String addr=hm.get(stu);
System.out.println(stu+"地址:"+addr);
}
//第二种取出方式 entrySet
Set<Map.Entry<Student,String>> entrySet=hm.entrySet();
Iterator<Map.Entry<Student,String>> iter=entrySet.iterator();
//获取键值对,再获取键和值
while (iter.hasNext())
{
Map.Entry<Student,String> m=iter.next();
Student stu=m.getKey();
String addr=m.getValue();
System.out.println(stu+"地址:"+addr);
}
}
}
//name--place
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(new Integer(s.age));
if (num==0)
return this.name.compareTo(s.name);
return num;
}
public int hashiCode()//复写hashCode
{
return name.hashCode()+age*34;
}
public boolean equals(Object object)//复写equals
{
if (!(object instanceof Student))
throw new ClassCastException("类型不匹配");
Student s=(Student)object;
return this.name.equals(s.name)&&this.age==s.age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name+":"+age;
}
}
对于任何的类,只要需要往哈希表里面传,就需要重写hashCode()和equals(),
TreeMap练习1,需求:对学生对象的姓名进行升序排序
因为数据是以键值对形式存在的.
所以要使用可以排序的Map集合:treeMap
public class Main {
public static void main(String[] args) {
// write your code here
TreeMap<Student, String> hm = new TreeMap<Student, String>(new StuNameComparetor());
//添加元素
hm.put(new Student("zhangsan", 18), "beijing");
hm.put(new Student("lisi", 19), "nanjing");
hm.put(new Student("wangwu", 17), "tianjing");
hm.put(new Student("zhaoliu", 20), "wuhan");
hm.put(new Student("zefaer", 21), "chengdu");
Set<Map.Entry<Student, String>> entrySet = hm.entrySet();
//获取迭代器
Iterator<Map.Entry<Student, String>> it = entrySet.iterator();
while (it.hasNext()) {
Map.Entry<Student, String> m = it.next();
Student stu = m.getKey();
String addr = m.getValue();
System.out.println(stu + ":::" + addr);
}
}
}
/*
如果不加比较器,无法按姓名排序。
*/
class StuNameComparetor implements Comparator<Student>
{
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 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(new Integer(s.age));
if (num==0)
return this.name.compareTo(s.name);
return num;
}
public int hashiCode()//复写hashCode
{
return name.hashCode()+age*34;
}
public boolean equals(Object object)//复写equals
{
if (!(object instanceof Student))
throw new ClassCastException("类型不匹配");
Student s=(Student)object;
return this.name.equals(s.name)&&this.age==s.age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name+":"+age;
}
}
TreeMap2 字母出现的次数
统计字符串中字母的出现次数
"sdfgzxcvasdfxcvdf"获取该字符串中的字母出现的次数。
希望打印结果: a(1)c(2)…
通过结果发现,每一一个字母都有对应的次数。
说明字母和次数之间都有映射关系。
注意了,当发现有映射关系时,可以选择map集合。
因为map集合中存放就是映射关系。
什么使用map集合呢?
当数据之间存在这映射关系时,就要先想map集合。
思路:
1,将字符串转换成字符数组。因为要对每一个字母进行操作。
2,定义一个map集合,因为打印结果的字母有顺序,所以使用treemap集合。
3,遍历字符数组。将每一个字母作为键去查map集合。如果返回null,将该字母和1存入到map集合中。如果返回不是null,说明该字母在map集合已经存在并有对应次数。那么就获取该次数并进行自增。然后将该字母和自增后的次数存入到map集合中。覆盖调用原理键所对应的值。
4,将map集合中的数据编程指定的字符串形式返回。
public class Main {
public static void main(String[] args) {
// write your code here
charCount("sdfgzxcvasdfxcvdf");
}
public static void charCount(String str)
{
char[] chs=str.toCharArray();
//定义map集合
TreeMap<Character,Integer> m=new TreeMap<Character,Integer>();
for (int i = 0; i < chs.length; i++)
{
Integer value=m.get(chs[i]);//获取值
if (value==null)
{
m.put(chs[i],1);//第一次出现则值为一
}
else
{
value++;
m.put(chs[i],value);
}
}
StringBuilder sb=new StringBuilder();
Set<Map.Entry<Character,Integer>>entrySet=m.entrySet();
Iterator<Map.Entry<Character,Integer>> it=entrySet.iterator();
while (it.hasNext())
{
Map.Entry<Character,Integer> mm=it.next();
Character ch=mm.getKey();
Integer value=mm.getValue();
sb.append(ch+"("+value+") ");
}
System.out.println(sb);
}
}
因为Character实现了Comparable接口,所以实现了排序。
再稍微优化一下。
public class Main {
public static void main(String[] args) {
// write your code here
charCount("sdfgzxcvasdfxcvdf");
}
public static void charCount(String str)
{
char[] chs=str.toCharArray();
//定义map集合
int count=0;
TreeMap<Character,Integer> m=new TreeMap<Character,Integer>();
for (int i = 0; i < chs.length; i++)
{
if (!(chs[i]>='a'&&chs[i]<='z'||chs[i]>='A'&&chs[i]<='Z'))
{
continue;
}
Integer value=m.get(chs[i]);//获取值
if (value!=null)
{
count=value;
}
count++;
m.put(chs[i],count);
count=0;
}
System.out.println(m);
//
StringBuilder sb=new StringBuilder();
Set<Map.Entry<Character,Integer>>entrySet=m.entrySet();
Iterator<Map.Entry<Character,Integer>> it=entrySet.iterator();
while (it.hasNext())
{
Map.Entry<Character,Integer> mm=it.next();
Character ch=mm.getKey();
Integer value=mm.getValue();
sb.append(ch+"("+value+") ");
}
System.out.println(sb);
}
}