------http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
一、概述
Map集合接口在JAVA中的util包中。在Map中存储的是键值对,它的key则是不能重复存储的,是唯一的。在Map接口中有很多的子类,本文只介绍它常用的两个子类,HashMap和TreeMap。
二、举例
示例一、
/*
* Map集合特点:存储的是键值对, 保证键的唯一性.
* 1.存储
* put(K key, V value)
* putAll(Map extends K,? extends V> m)
*
* 2.删除
* void clear()
* remove(Object key)
*
* 3.判断
* boolean containsKey(Object key) //集合中是否包含某个key
* boolean containsValue(Object value) //集合中是否包含某个value
* boolean isEmpty()
*
* 4.获取
* get(Object key) //根据指定的key获取value
* size()
* values()
* entrySet() //返回此映射中包含的映射关系的 Set视图
* keySet() //返回此映射中包含的键的 Set视图
*
*
* Map
* |--HashTable: 底层是hash表数据结构, 键和值都不能为null, 该集合是线程同步的
* |--HashMap: 底层是hash表数据结构, 键和值允许为null, 该集合是线程不同步的
* |--TreeMap: 底层是二叉树数据结构, 线程不同步, 可以用于给map集合中的键排序
*
* Set集合底层使用了Map集合.
*
*
*/
public class MapDemo {
public static void main(String[] args) {
Map map = new HashMap();
//添加元素,
//如果该key不存在, 则添加进去, 并返回null.
//如果该key已经在集合中存在, 则后添加的value覆盖原来对应的value, 并返回原来对应的value
map.put("01", "张三");
map.put("02", "李四");
map.put("03", "王五");
map.put("04", "找牛");
//判断是否包含01key
boolean b = map.containsKey("01");
System.out.println(b);
//判断是否包含value
b = map.containsValue("张三");
System.out.println(b);
//判断是否为空
b = map.isEmpty();
System.out.println(b);
//返回集合中有多少元素
int size = map.size();
System.out.println(size);
//返回key对应的value, 如果该key不存在, 则返回null
String s = map.get("01");
System.out.println(s);
//根据key删除该键值对, 并返回该key对应的value
String str = map.remove("01");
System.out.println(str);
//返回Map集合中所有的value
Collection coll = map.values();
for(Iterator it = coll.iterator();it.hasNext();){
System.out.println(it.next());
}
//返回Map集合中所有的key
Set set = map.keySet();
for(Iterator it = set.iterator();it.hasNext();){
String key = it.next();
System.out.println("key : " + key);
String value = map.get(key);
System.out.println("value : " + value);
}
}
}
示例二、
/*
* Map集合的两种取出方式:
* Set keySet: 将map中所有的key存入了set集合中
*
* Map集合的取出原理: 将Map集合转成Set集合, 再通过迭代器取出.
*
* Set> entrySet: 将Map集合中的映射关系存入Set集合中, 这个关系的数据类型就是: Map.Entry
*
* Map.Entry:
* Entry是一个接口, 它是Map中的一个内部接口.
*
*
*
*/
public class MapDemo2 {
public static void main(String[] args) {
Map map = new HashMap();
map.put("01", "张三");
map.put("02", "李四");
map.put("03", "王五");
map.put("04", "找牛");
Set set = map.keySet();
for(Iterator it = set.iterator();it.hasNext();){
String key = it.next();
String value = map.get(key);
System.out.println(value);
}
Set> setEntry = map.entrySet();
for(Iterator> it = setEntry.iterator();it.hasNext();){
Map.Entry en = it.next();
String key = en.getKey();
System.out.println("key : " + key);
if("01".equals(key))
en.setValue("zhangsan");
String value = en.getValue();
System.out.println("value : " + value);
}
}
}
示例三、TreeMap示例
//按照学生的年龄进行升序排序
public class TreeMap练习 {
public static void main(String[] args) {
Map map = new TreeMap(new Comp());
map.put(new Student("t", 12), "dadadadadafaf");
map.put(new Student("J", 7), "dadadewd");
map.put(new Student("a", 5), "dadadad444");
Set> entries = map.entrySet();
for (Iterator> it = entries.iterator(); it.hasNext();) {
Map.Entry me = it.next();
Student s = me.getKey();
System.out.println("student -> " + s);
String addr = me.getValue();
System.out.println("addr -> " + addr);
}
}
}
//自定义比较器
class Comp implements Comparator{
@Override
public int compare(Student o1, Student o2) {
int num = (o1.getName().compareTo(o2.getName()))*1;
// System.out.println(" --------------- " + num);
if(0==num)
return (new Integer(o1.getAge()).compareTo(new Integer(o2.getAge())));
return num;
}
}
class Student implements Comparable {
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) {
if (!(obj instanceof Student))
// throw new RuntimeException("类型匹配错误!");
throw new ClassCastException("类型不匹配.");
Student stu = (Student) obj;
return (this.getName().equals(stu.getName()) && this.getAge() == stu.getAge());
}
@Override
public int hashCode() {
return this.getName().hashCode() + this.getAge() * 27;
}
@Override
public String toString() {
return "Name : " + this.getName() + ", age : " + this.getAge();
}
@Override
public int compareTo(Student o) {
int num = new Integer(this.age).compareTo(new Integer(o.getAge()));
if (0 == num)
return this.getName().compareTo(o.getName());
return num;
}
}
示例四、
//统计字符串中字符出现的次数, 如: "adadggwsf", 统计面一个字符出现的次数
//打印为:a(2)d(2).....
public class TreeMap练习2 {
public static void main(String[] args) {
String str = "adadg,.g;wsf";
char[] ch = new char[str.length()];
str.getChars(0, str.length(), ch, 0);
// for(int i =0;i map = new TreeMap();
//遍历char数组
for (int i = 0; i < ch.length; i++) {
char temp = ch[i];
if(!(temp>='a'&&temp<='z')||(temp>='A'&&temp<='Z'))
continue;
Character c = new Character(temp);
//如果key存在, 则取出value, 并+1, 再存进去;
//如果key不存在, 则直接存进去, value = 1
if (map.containsKey(c)) {
map.put(c, map.get(c).intValue() + 1);
} else {
map.put(c, new Integer(1));
}
}
//迭代器遍历Map集合
StringBuilder sb = new StringBuilder();
Set> set = map.entrySet();
for (Iterator> it = set.iterator(); it.hasNext();) {
Map.Entry me = it.next();
String key = Character.toString(me.getKey().charValue());
String value = Integer.toString(me.getValue().intValue());
sb.append(key + "(" + value + ")");
}
System.out.println(sb.toString());
}
}