Java基础<十二>--->集合之map

时间:2022-02-16 15:15:06

Map集合

一、概述:Map<K,V>集合是一个接口:该集合存储键值对。一对一对往里存。而且要保证键的唯一性。

二、方法简介:

1、添加 put(K key, V value) 以键值对的形式往里存

putAll(Map<? extends K,? extends V> m) 把一个map里的内容作为值存入进map中。
2、删除 clear() 清空集合

remove(Object key) 清楚其中的一条
3、判断 containsValue(Object value) 判断map中是否包含某个值

containsKey(Object key) 判断map中是否包含某个值

isEmpty()判空
4、获取 get(Object key) 根据key获取值

size() 获取map集合的大小

values() 获取map中所有的值,并存放在Collection中        

entrySet()    Set<Map.Entry<K,V>>返回键值对关系,并存放在Set集合中
keySet() 获取map集合中所有的键并存放在Set集合中

a、也可以通过get()方法的返回值来判断一个键是否存在,通过返回null来判断。 b、其中put方法:如果出现添加相同的键,那么后添加的值会覆盖原有键对应的值,并且该方法返回被覆盖的值即原值。
import java.util.*;
class MapDemo
{
public static void main(String[] args)
{
Map<String,String> map = new HashMap<String,String>();

//添加元素,添加元素,如果出现添加时,相同的键。那么后添加的值会覆盖原有键对应值。
//并put方法会返回被覆盖的值。
System.out.println("put:"+map.put("01","zhangsan1"));
System.out.println("put:"+map.put("01","wnagwu"));//当存入相同键时,后存入的值会覆盖点以前的值,并返回以前的值,以前没值就放回null
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);
}
}
三、Map长见子类:
1、Hashtable:底层是哈希表数据结构,不可以存入null键null值。线程同步。被hashmap代替。 2、HashMap:底层是哈希表数据结构,允许null键null值,线程不同步。效率高 3、TreeMap:底层是二叉树数据结构。线程不同步,可以用于给map键值进行排序。 :Set底层就是使用了Map集合。
四、两种获取集合元素的方法:
1、keySet()方法获取元素原理:将Map集合中的所有键存入到Set集合中,因为Set集合具备迭代器,所以可以用迭代方式取出所有的键,再根据get方法获取每一个键对应的值。简单说就是:Map集合---->Set集合 ---->迭代器取出
import java.util.*;


class MapDemo2
{
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方法获取其对应的值。
String value = map.get(key);
System.out.println("key:"+key+",value:"+value);
}

}
}
2、entrySet()方法获取元素:原理:将Map集合中的映射关系存入到了Set集合中,而这个映射关系的数据类型是Map.Entry,在通过迭代器将映射关系存入到Map.Entry集合中,并通过其中的getKey()和getValue()放取出键值。
import java.util.*;


class MapDemo2
{
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);

}
}
}
补充:关于Map.EntryMap是一个接口,其实,Entry也是一个接口,它是Map的子接口中的一个内部接口,就相当于是类中有内部类一样。为何要定义在其内部呢?原因:a.Map集合中存的是映射关系这样的两个数据,是先有Map这个集合,才可有映射关系的存在,而且此类关系是集合的内部事务。b.并且这个映射关系可以直接访问Map集合中的内部成员,所以定义在内部。五、Map集合的应用及扩展:何时使用Map集合:当量数据之间存在着映射关系的时候,就应该想到使用Map集合。事例:获取该字符串中的字母出现的次数,如:“ak+abAf1c,dCkaAbc-defa"希望打印的结果是:a(3)c(0).....通过结果发现,每个字母都有对应的次数,说明字母和次数之间有映射关系。测试如下:
import java.util.*;
class MapTest3
{
public static void main(String[] args)
{
String s= charCount("ak+abAf1c,dCkaAbc-defa");
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]<='Z'))
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();
Character ch = me.getKey();
Integer value = me.getValue();
sb.append(ch+"("+value+")");
}



return sb.toString();
}

}
关于map的练习:
/*
每一个学生都有对应的归属地。
学生Student,地址String。
学生属性:姓名,年龄。
注意:姓名和年龄相同的视为同一个学生。
保证学生的唯一性。

1,描述学生。
2,定义map容器。将学生作为键,地址作为值。存入。
3,获取map集合中的元素。
*/
public class MapTest1 {
public static void main(String[] args) {
//保证学生唯一性的实现
HashMap<Student_1, String> map = new HashMap<Student_1, String>();
map.put(new Student_1("lisi1", 12), "beijing");
map.put(new Student_1("lisi2", 14), "sic");
map.put(new Student_1("lisi3", 10), "tianjin");
map.put(new Student_1("lisi4", 9), "sh");
// map.put(new Student_1("lisi4", 9), "hn");

//keySet_method(map);
//entrySet_method(map);

//用TreeMap实现对学生按照年龄排序
TreeMap<Student_1, String> tmap = new TreeMap<Student_1, String>(new StuNameComparator());
tmap.put(new Student_1("zhang01", 40), "beijing");
tmap.put(new Student_1("zhang05", 10), "sic");
tmap.put(new Student_1("zhang01", 10), "sic");
tmap.put(new Student_1("zhang04", 20), "sh");
//tmap.put(new Student_1("zhang04", 20), "sh12");
tmap.put(new Student_1("zhang03", 30), "nj");

keySet_method(tmap);
entrySet_method(tmap);
}

public static void keySet_method(Map<Student_1, String> map) {
Set<Student_1> keySet = map.keySet();

for (Iterator<Student_1> it = keySet.iterator(); it.hasNext();) {
Student_1 stu = it.next();
String address = map.get(stu);
print(stu + "......." + address);
}
}

public static void entrySet_method(Map<Student_1, String> map) {
Set<Map.Entry<Student_1, String>> entrySet = map.entrySet();

for (Iterator<Map.Entry<Student_1, String>> it = entrySet.iterator(); it
.hasNext();) {
Map.Entry<Student_1, String> me = it.next();
Student_1 stu = me.getKey();
String address = me.getValue();
print(stu + ".....entry....." + address);
}
}

private static void print(Object obj) {
System.out.println(obj);
}
}

/*
* 建立学生类,因为需要学生本身具备比较性,所以实现了comparable重写了compareTo方法
* 因为可能被存放在hash表中,所以需要重写hashcode和equals方法
*/
class Student_1 implements Comparable<Student_1> {

@Override
public String toString() {
return name + "::" + age;
}

private String name;
private int age;

Student_1(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 int compareTo(Student_1 o) {
int num = this.age - o.getAge();
if (num == 0) {
this.name.compareTo(o.getName());
}

return num;
}

@Override
public int hashCode() {
return name.hashCode() + this.age * 10;
}

@Override
public boolean equals(Object obj) {
if (!(obj instanceof Student_1)) {
throw new ClassCastException();
}
Student_1 s = (Student_1) obj;

return this.name.equals(s.name) && this.age == s.age;
}
}

/*
* 将学生年龄进行升序排序
* 用TreeMap实现
*/
class StuNameComparator implements Comparator<Student_1> {

@Override
public int compare(Student_1 o1, Student_1 o2) {
int num = new Integer(o1.getAge()).compareTo(new Integer(o2.getAge()));

if(num == 0){
return o1.getName().compareTo(o2.getName());
}
return num;
}

}