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()
entrySet()
keySet()
Map
Hashtable:底层是哈希表数据结构,不可以存入null键null值。该集合是线程同步的。jdk1.0,效率低。
HashMap:底层是哈希表数据结构,允许使用null键null值,该集合是不同步的。将hashtable替代,jdk1.2,效率高。
TreeMap:底层是二叉树数据结构。线程不同步。可以用于给map集合中的键进行排序。
和Set很像。
其实大家,set底层就是使用了Map集合。
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class MapDemo {
public static void main(String[] args) {
Map<String,String> map = new HashMap<String,String>();
//添加元素,如果出现添加时,相同的键。那么后添加的值会覆盖原有键对应值。
System.out.println("put:"+map.put("01","zhangsan1"));
System.out.println("put:"+map.put("01","wangwu"));
map.put("02","zhangsan2");
map.put("03","zhangsan3");
System.out.println("containsKey:"+map.containsKey("022"));
// System.out.println("remove:"+map.remove("02"));
System.out.println("get:"+map.get("023"));
map.put("04",null);
System.out.println("get:"+map.get("04"));
//可以通过get方法的返回值来判断一个键是否存在。通过返回null来判断。
//获取map集合中所有的值。
Collection<String> coll = map.values();
System.out.println(coll);
System.out.println(map);
}
}
//输出
put:null
put:zhangsan1
containsKey:false
get:null
get:null
[wangwu, zhangsan2, zhangsan3, null]
{01=wangwu, 02=zhangsan2, 03=zhangsan3, 04=null}
Map集合的两种取出方式:
- 1.keySet:将map中所有的键存入到Set集合。因为set具备迭代器。所有可以迭代方式取出所有的键,在根据get方法。获取每一个键对应的值。Map集合的取出原理:将map集合转成set集合。再通过迭代器取出。
- Set<Map.Entry<k,v>> entrySet:将map集合中的映射关系存入到了set集合中,而这个关系的数据类型就是:Map.Entry。
import java.util.*;
public class MapDemo0 {
public static void main(String[] args) {
Map<String,String> map = new HashMap<String,String>();
map.put("02","zhangsan2");
map.put("03","zhangsan3");
map.put("01","zhangsan1");
map.put("04","zhangsan4");
//先获取map集合的所有键的Set集合,keySet();
Set<String> keySet = map.keySet();
//有了Set集合,就可以获取其迭代器。
Iterator<String> it = keySet.iterator();
while (it.hasNext())
{
String key = it.next();
//有了键可以通过map集合的get方法获取其对应的value
String value = map.get(key);
System.out.println("key:"+key+",value:"+value);
}
}
}
//输出
key:01,value:zhangsan1
key:02,value:zhangsan2
key:03,value:zhangsan3
key:04,value:zhangsan4
Map.Entry其实Entry也是一个接口,它是Map接口中的一个内部接口。
Interface Map
{
public static Interface Entry
{
public abstract Object getKey();
public abstract Object getValue();
}
}
class HashMap implements Map
{
class Haha implements Map.Entry
{
public Object getKey(){}
public Object getValue(){}
}
}
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class MapDemo1 {
public static void main(String[] args) {
Map<String,String> map = new HashMap<String,String>();
map.put("02","zhangsan2");
map.put("03","zhangsan3");
map.put("01","zhangsan1");
map.put("04","zhangsan4");
//将Map集合中的映射关系取出,存入到Set集合中。
Set<Map.Entry<String,String>> entrySet = map.entrySet();
Iterator<Map.Entry<String,String>> it = entrySet.iterator();
while (it.hasNext())
{
Map.Entry<String,String> me = it.next();
String key = me.getKey();
String value = me.getValue();
System.out.println(key+":"+value);
}
}
}
//输出
01:zhangsan1
02:zhangsan2
03:zhangsan3
04:zhangsan4
每一个学生都有对应的归属地。学生Student,地址String。学生属性:姓名,年龄。注意:姓名和年龄相同的视为同一个学生。保证学生的唯一性。
1.描述学生。
2.定义map容器,将学生作为键,地址作为值,存入。
3.获取map集合中的元素。
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
class Student9 implements Comparable<Student9>
{
private String name;
private int age;
Student9(String name,int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name+":"+age;
}
public int hashCode()
{
return name.hashCode()+age*34;
}
public boolean equals(Object obj)
{
if (!(obj instanceof Student9))
throw new ClassCastException("类型不匹配");
Student9 s = (Student9) obj;
return this.name.equals(s.name)&& this.age==s.age;
}
public int compareTo(Student9 s)
{
int num = new Integer(this.age).compareTo(new Integer(s.age));
if (num == 0)
{
return this.name.compareTo(s.name);
}
return num;
}
}
public class MapDemo2 {
public static void main(String[] args) {
HashMap<Student9,String> hm = new HashMap<Student9,String>();
hm.put(new Student9("lisi1",21),"beijing");
hm.put(new Student9("lisi1",21),"tianjin");
hm.put(new Student9("lisi2",22),"shanghai");
hm.put(new Student9("lisi3",23),"nanjing");
hm.put(new Student9("lisi4",21),"wuhan");
//第一种取出方式 keySet
Set<Student9> keySet = hm.keySet();
Iterator<Student9> it = keySet.iterator();
while (it.hasNext())
{
Student9 stu = it.next();
String addr = hm.get(stu);
System.out.println(stu+".."+addr);
}
}
}
//输出
lisi2:22..shanghai
lisi4:21..wuhan
lisi1:21..tianjin
lisi3:23..nanjing
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
class Student10 implements Comparable<Student10>
{
private String name;
private int age;
Student10(String name,int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name+":"+age;
}
public int hashCode()
{
return name.hashCode()+age*34;
}
public boolean equals(Object obj)
{
if (!(obj instanceof Student10))
throw new ClassCastException("类型不匹配");
Student10 s = (Student10) obj;
return this.name.equals(s.name)&& this.age==s.age;
}
public int compareTo(Student10 s)
{
int num = new Integer(this.age).compareTo(new Integer(s.age));
if (num == 0)
{
return this.name.compareTo(s.name);
}
return num;
}
}
public class MapDemo3 {
public static void main(String[] args) {
HashMap<Student10,String> hm = new HashMap<Student10,String>();
hm.put(new Student10("lisi1",21),"beijing");
hm.put(new Student10("lisi1",21),"tianjin");
hm.put(new Student10("lisi2",22),"shanghai");
hm.put(new Student10("lisi3",23),"nanjing");
hm.put(new Student10("lisi4",21),"wuhan");
//第二种取出方式 Map.Entry
Set<Map.Entry<Student10,String>> map = hm.entrySet();
Iterator<Map.Entry<Student10,String>> iter = map.iterator();
while (iter.hasNext())
{
Map.Entry<Student10, String> me = iter.next();
Student10 stu = me.getKey();
String addr = me.getValue();
System.out.println(stu+".."+addr);
}
}
}
//输出
lisi2:22..shanghai
lisi4:21..wuhan
lisi1:21..tianjin
lisi3:23..nanjing
对学生对象的年龄进行升序排列。
因为数据是以键值对形式存在的。所以要使用可以排序的Map集合。TreeMap。
import java.util.*;
class Student10 implements Comparable<Student10>
{
private String name;
private int age;
Student10(String name,int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name+":"+age;
}
public int hashCode()
{
return name.hashCode()+age*34;
}
public boolean equals(Object obj)
{
if (!(obj instanceof Student10))
throw new ClassCastException("类型不匹配");
Student10 s = (Student10) obj;
return this.name.equals(s.name)&& this.age==s.age;
}
public int compareTo(Student10 s)
{
int num = new Integer(this.age).compareTo(new Integer(s.age));
if (num == 0)
{
return this.name.compareTo(s.name);
}
return num;
}
}
class StuNameComparator implements Comparator<Student10>
{
public int compare(Student10 s1,Student10 s2)
{
int num = s1.getName().compareTo(s2.getName());
if (num == 0)
{
return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
}
return num;
}
}
public class MapDemo3 {
public static void main(String[] args) {
TreeMap<Student10,String> hm = new TreeMap<Student10,String>(new StuNameComparator());
hm.put(new Student10("lisi1",21),"beijing");
// hm.put(new Student10("lisi1",21),"tianjin");
hm.put(new Student10("lisi2",22),"shanghai");
hm.put(new Student10("lisi3",23),"nanjing");
hm.put(new Student10("lisi4",21),"wuhan");
hm.put(new Student10("blisi",21),"hangzhou");
hm.put(new Student10("clisi",21),"suzhou");
//第二种取出方式 Map.Entry
Set<Map.Entry<Student10,String>> map = hm.entrySet();
Iterator<Map.Entry<Student10,String>> iter = map.iterator();
while (iter.hasNext())
{
Map.Entry<Student10, String> me = iter.next();
Student10 stu = me.getKey();
String addr = me.getValue();
System.out.println(stu+".."+addr);
}
}
}
//输出
blisi:21..hangzhou
clisi:21..suzhou
lisi1:21..beijing
lisi2:22..shanghai
lisi3:23..nanjing
lisi4:21..wuhan
练习:"sdfgzxcvasdfxcvdf"获取该字符串中的字母出现的次数。希望打印结果:a(1)c(2)......
通过结果发现,每一个字母都有对应的次数。
说明字母和次数之间都有映射关系。
注意了,当发现有映射关系时,可以选择map集合。
因为map集合中存放就是映射关系。
什么时候使用map集合呢?
当数据之间存在这映射关系时,就要先想map集合。
思路:
- 1.将字符串转换成字符数组。因为要对每一个字母进行操作。
- 2.定义一个map集合,因为打印结果的字母有顺序,所以使用treemap集合。
- 3.遍历字符数组。将每一个字母作为键去查map集合。如果返回null,将该字母和1存入到map集合中。如果返回不是null,说明该字母在map集合已经存在并有对应次数。那么就获取该次数并进行自增。然后将该字母和自增后的次数存入到map集合中,覆盖掉原来键所对应的值。
- 4.将map集合中的数据变成指定的字符串形式返回。
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class MapDemo4 {
public static void main(String[] args) {
String s = charCount("abcdacd,+kvnmenad-bc");
System.out.println(s);
}
public static String charCount(String str)
{
char[] chs = str.toCharArray();
TreeMap<Character,Integer> tm = new TreeMap<Character, Integer>();
int count = 0;
for (int x=0;x<chs.length;x++)
{
if (!(chs[x]>='a' && chs[x]<='z' || chs[x]>='A'&&chs[x]<='X'))
continue;
Integer value = tm.get(chs[x]);
if (value!=null)
count = value;
count++;
tm.put(chs[x],count);
count = 0;
/*
if (value == null)
tm.put(chs[x],1);
else
{
value = value + 1;
tm.put(chs[x],value);
}
*/
}
System.out.println(tm);
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();
sb.append(me.getKey()+"("+me.getValue()+")");
}
return sb.toString();
}
}
//输出
{a=3, b=2, c=3, d=3, e=1, k=1, m=1, n=2, v=1}
a(3)b(2)c(3)d(3)e(1)k(1)m(1)n(2)v(1)
Map扩展知识。
map集合被使用是因为具备映射关系。
"yureban" Student("01" "zhangsan");
"yureban" Student("02" "lisi");
"jiuyeban" "01" "wangwu";
"jiuyeban" "02" "zhaoliu";
一个学校有多个教室。每一个教室都有名称。
import java.util.HashMap;
import java.util.Iterator;
public class MapDemo5 {
public static void main(String[] args) {
HashMap<String,HashMap<String,String>> czbk = new HashMap<String,HashMap<String, String>>();
HashMap<String,String> yure = new HashMap<String,String>();
HashMap<String,String> jiuye = new HashMap<String,String>();
czbk.put("yureban",yure);
czbk.put("jiuyeban",jiuye);
yure.put("01","zhangsan");
yure.put("02","lisi");
jiuye.put("01","zhaoliu");
jiuye.put("02","wangwu");
//遍历czbk集合。获取所有的教室。
Iterator<String> it = czbk.keySet().iterator();
while (it.hasNext())
{
String rootName = it.next();
HashMap<String,String> room = czbk.get(rootName);
System.out.println(rootName);
getStudentInfo(room);
}
// getStudentInfo(yure);
// getStudentInfo(jiuye);
}
public static void getStudentInfo(HashMap<String,String> roomMap)
{
Iterator<String> it = roomMap.keySet().iterator();
while (it.hasNext())
{
String id = it.next();
String name = roomMap.get(id);
System.out.println(id+":"+name);
}
}
}
//输出
jiuyeban
01:zhaoliu
02:wangwu
yureban
01:zhangsan
02:lisi
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
class Student11
{
private String id;
private String name;
Student11(String id,String name)
{
this.id = id;
this.name = name;
}
public String getId(){
return id;
}
public String getName()
{
return name;
}
public String toString()
{
return id+":::"+name;
}
}
public class MapDemo6 {
public static void main(String[] args) {
HashMap<String,List<Student11>> czbk = new HashMap<String, List<Student11>>();
List yure = new ArrayList<Student11>();
List jiuye = new ArrayList<Student11>();
czbk.put("yureban",yure);
czbk.put("jiuyeban",jiuye);
yure.add(new Student11("01","zhangsan"));
yure.add(new Student11("04","wangwu"));
jiuye.add(new Student11("01","zhouqi"));
jiuye.add(new Student11("02","zhaoliu"));
Iterator<String> it = czbk.keySet().iterator();
while (it.hasNext())
{
String roomName = it.next();
List<Student11> room = czbk.get(roomName);
System.out.println(roomName);
getInfos(room);
}
}
public static void getInfos(List<Student11> list)
{
Iterator<Student11> it = list.iterator();
while (it.hasNext())
{
Student11 s = it.next();
System.out.println(s);
}
}
}
//输出
jiuyeban
01:::zhouqi
02:::zhaoliu
yureban
01:::zhangsan
04:::wangwu