java基础-Map集合

时间:2021-11-13 14:32:14

                  java基础-Map集合

                                作者:尹正杰

版权声明:原创作品,谢绝转载!否则将追究法律责任。

一.Map集合概述

  我们通过查看Map接口描述,发现Map接口下的集合与Collection接口下的集合,它们存储数据的形式不同,如下:

1>.Collection中的集合,元素是孤立存在的,向集合中存储元素采用一个个元素的方式存储;

2>.Map中的集合,元素是成对存在的,每个元素是成对存在的,每个元素由键和值两部分组成,通过键可以找到对应的值;

3>Collection中的集合称为单列集合,Map中的集合称为双列集合;

4>.需要注意的是,Map中的集合不能包含重复的键,值可以重复;每个键只能对应一个值;

5>.Map中常用的集合为HashMap集合,LinkHashMap集合;

6>.Map存储元素使用put方法,Collection使用add发明合法;

7>.Map集合没有直接取出元素的方法,而是先转成Set集合,再通过迭代获取元素;

8>.Map集合中键要保证唯一性;

二.Map接口中常用集合概述

  通过查看Map接口描述,看到Map有多个子类,我们Map集合常用类大概分为以下几种:

1>.Hashtable

  线程安全,速度慢,不允许存放null键和null值,已被HashMap替代。

2>.HashMap

  线程不安全,速度块,允许存放null键和null值。

3>.LinkedHashMap

  Map 接口的哈希表和链接列表实现,具有可预知的迭代顺序。是HashMap的链表实现(可以用IDE查看源码),由哈希表保证了键的唯一性,由链表保证了元素的存取顺序。

4>.TreeMap

  对键进行排序,排序原理 与TreeSet相同。

  注意:Map接口中的结合都有两个泛型变量<K,V>,在使用时,要为两个泛型变量赋予数据类型。两个泛型变量<K,V>的数据类型可以相同,也可以不同。

三.Map接口中的常用方法

1>.V put(K,V)方法【将键值对存储到集合中,K作为键的对象,V作为值的对象】

 /*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/ package cn.org.yinzhengjie.note3; import java.util.HashMap;
import java.util.Map; public class MapDemo {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
Integer i = map.put("a", 100); //第一次存储,返回值为空
System.out.println(i);
i = map.put("a", 200); //以及存在“a”这个key,因此不会写入,返回存在key所对应的value。
System.out.println(i);
map.put("b", 200);
map.put("c", 100);
map.put("d", 300);
System.out.println(map);
}
} /*
以上代码执行结果如下:
null
100
{a=200, b=200, c=100, d=300}
*/

2>.V get(K)方法【通过键对象,获取值对象】

 /*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/ package cn.org.yinzhengjie.note3; import java.util.HashMap;
import java.util.Map; public class MapDemo {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "yinzhengjie");
map.put(2, "尹正杰");
map.put(3, "2018");
System.out.println(map);
String res = map.get(5); //如果key在map中不存在就返回空
System.out.println(res);
res = map.get(2); //如果key在map中存在就返回具体的value
System.out.println(res);
}
} /*
以上代码执行结果如下:
{1=yinzhengjie, 2=尹正杰, 3=2018}
null
尹正杰
*/

3>.V remove(K)方法【根据指定的键删除元素,返回被删除元素的值】

 /*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/ package cn.org.yinzhengjie.note3; import java.util.HashMap;
import java.util.Map; public class MapDemo {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "yinzhengjie");
map.put(2, "尹正杰");
map.put(3, "2018");
String res = map.remove(3);
System.out.println(res);
res = map.remove(4);
System.out.println(res);
System.out.println(map);
}
} /*
以上代码执行结果如下:
2018
null
{1=yinzhengjie, 2=尹正杰}
*/

4>.int size()方法【返回的是map集合中的长度】

 /*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/ package cn.org.yinzhengjie.note3; import java.util.HashMap;
import java.util.Map; public class MapDemo {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "yinzhengjie");
map.put(2, "尹正杰");
map.put(3, "2018");
int lenth = map.size();
System.out.println(lenth);
}
} /*
以上代码执行结果如下:
3
*/

四.Map集合遍历方式

1>.KeySet方法

 /*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/ package cn.org.yinzhengjie.note3; import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set; public class MapDemo {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "yinzhengjie");
map.put(2, "尹正杰");
map.put(3, "2018"); //调用map集合的方法keySet,所有的键存储到Set集合中
Set<Integer> set = map.keySet();
//我们可以查看set类的全名,可以看出它是HashMap的内部类
System.out.println(set.getClass());
//遍历set集合,获取出Set集合中的所有元素(Map中的键)
Iterator<Integer> it = set.iterator();
while(it.hasNext()) {
//it.next()方法返回的是Set集合元素,也就是Map中的键
Integer key = it.next();
//调用map集合的get方法,通过Map中的键获取其对应的value
String value = map.get(key);
System.out.println(key + "---" + value);
}
System.out.println("---$$$$$$$$$$$$$$$$$$$$$$$---");
//增强for循环编译后其实还是迭代器形式,并且在写法上要比上面的写法要简单的多。
for (Integer key : map.keySet()) {
String value = map.get(key);
System.out.println(key + "---" + value);
}
}
} /*
以上代码执行结果如下:
class java.util.HashMap$KeySet
1---yinzhengjie
2---尹正杰
3---2018
---$$$$$$$$$$$$$$$$$$$$$$$---
1---yinzhengjie
2---尹正杰
3---2018
*/

2>.Map集合Entry对象

  在Map类设计时,提供了一个嵌套接口:Entry。Entry将键值对的对应关系封装成了对象。即键值对对象,这样我们在遍历Map集合时,就可以从每一个键值对(Entry)对象中获取对应的键与对应的值。

 /*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/ package cn.org.yinzhengjie.note3; import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; public class MapDemo {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "yinzhengjie");
map.put(2, "尹正杰");
map.put(3, "2018"); //调用map集合方法entrySet()将集合中的映射关系对象,存储到Set集合
Set<Map.Entry<Integer, String>> set = map.entrySet();
//迭代Set集合
Iterator<Entry<Integer, String>> it = set.iterator();
while(it.hasNext()) {
//获取出的Set集合的元素是映射关系,it.next()也是Map.Entry对象
Entry<Integer, String> entry = it.next();
Integer key = entry.getKey();
String value = entry.getValue();
System.out.println(key+"---"+value);
}
System.out.println("###############################");
//注意,增强for循环(foreach)不能遍历map!下面我遍历的是集合,并非是map哟!不要被面试官忽悠了 !
for(Map.Entry<Integer,String> entry : map.entrySet()) {
System.out.println(entry.getKey() + "..." + entry.getValue());
}
}
} /*
以上代码执行结果如下:
1---yinzhengjie
2---尹正杰
3---2018
###############################
1...yinzhengjie
2...尹正杰
3...2018
*/

五.HashMap集合存储和遍历

1>.自定义类当value时常用遍历方式

 /*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/ package cn.org.yinzhengjie.note3; public class Person {
private String Name;
private int Age;
public Person() {
super();
}
public Person(String name, int age) {
super();
Name = name;
Age = age;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
}

Person.java 文件内容

 /*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/ package cn.org.yinzhengjie.note3; import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; public class MapDemo {
public static void main(String[] args) {
HashMap<String, Person> map = new HashMap<>();
map.put("beijing", new Person("yinzhengjie",18));
map.put("西安", new Person("尹正杰",20));
map.put("安康", new Person("邓西",25));
System.out.println("第一种遍历方式:");
for(String key : map.keySet()) {
Person value = map.get(key);
System.out.println("\t"+key + "..." + value);
}
System.out.println("第二种遍历方式:");
for (Entry<String, Person> entry : map.entrySet()) {
String key = entry.getKey();
Person value = entry.getValue();
System.out.println("\t"+key + "..." + value);
}
}
} /*
以上代码执行结果如下:
第一种遍历方式:
安康...cn.org.yinzhengjie.note3.Person@424c0bc4
beijing...cn.org.yinzhengjie.note3.Person@3c679bde
西安...cn.org.yinzhengjie.note3.Person@16b4a017
第二种遍历方式:
安康...cn.org.yinzhengjie.note3.Person@424c0bc4
beijing...cn.org.yinzhengjie.note3.Person@3c679bde
西安...cn.org.yinzhengjie.note3.Person@16b4a017
*/

2>.自定义当key时常用遍历方式

 /*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/ package cn.org.yinzhengjie.note3; public class Person {
private String Name;
private int Age;
public Person() {
super();
}
public Person(String name, int age) {
super();
Name = name;
Age = age;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Age;
result = prime * result + ((Name == null) ? 0 : Name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (Age != other.Age)
return false;
if (Name == null) {
if (other.Name != null)
return false;
} else if (!Name.equals(other.Name))
return false;
return true;
} }

Person.java 文件内容

 /*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/ package cn.org.yinzhengjie.note3; import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; public class MapDemo {
public static void main(String[] args) {
HashMap<Person, String> map = new HashMap<>();
map.put(new Person("dengxi",20),"里约热内卢");
map.put(new Person("taotao",80),"索马里");
map.put(new Person("fangheyi",30),"百慕大");
map.put(new Person("yinzhengjie",65),"土耳其");
map.put(new Person("yinzhengjie",65),"土耳其");
System.out.println("第一种遍历方式:");
for(Person key : map.keySet()) {
String value = map.get(key);
System.out.println("\t"+key + "..." + value);
}
System.out.println("第二种遍历方式:");
for (Entry<Person, String> entry : map.entrySet()) {
Person key = entry.getKey();
String value = entry.getValue();
System.out.println("\t"+key + "..." + value);
}
}
} /*
以上代码执行结果如下:
第一种遍历方式:
cn.org.yinzhengjie.note3.Person@3085b5e4...百慕大
cn.org.yinzhengjie.note3.Person@f90f1314...土耳其
cn.org.yinzhengjie.note3.Person@cb7d5231...索马里
cn.org.yinzhengjie.note3.Person@b0677c98...里约热内卢
第二种遍历方式:
cn.org.yinzhengjie.note3.Person@3085b5e4...百慕大
cn.org.yinzhengjie.note3.Person@f90f1314...土耳其
cn.org.yinzhengjie.note3.Person@cb7d5231...索马里
cn.org.yinzhengjie.note3.Person@b0677c98...里约热内卢
*/

六.LinkedHashMap的特点

  linkedHashMap继承自HashMap,可以保证迭代的顺序

 /*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/ package cn.org.yinzhengjie.note3; import java.util.LinkedHashMap; public class LinkedHashmapDemo {
public static void main(String[] args) {
LinkedHashMap<String,Integer> link = new LinkedHashMap<>();
link.put("yinzhengjie", 18);
link.put("尹正杰", 18);
link.put("灵魂摆渡", 2018);
link.put("红海行动", 328);
link.put("神秘巨星",201712 );
link.put("摔跤吧,爸爸",201705 );
System.out.println(link);
}
} /*
以上代码执行结果如下:
{yinzhengjie=18, 尹正杰=18, 灵魂摆渡=2018, 红海行动=328, 神秘巨星=201712, 摔跤吧,爸爸=201705}
*/

七.Hashtable的特点

  Map接口实现类Hashtable,底层数据结构依然是哈希表,特点和HashMap是一样的,HashMap线程不安全的集合,运行速度尽快,Hashtable命运和Vector是一样的,从JDK1.2开始,被更先进的HashMap取代。HashMap允许存储null值,null键,Hashtable不允许存储null值,null键。

  尽管Hashtable虽然退出了历史舞台,但是它的孩子properties依然活跃在开发舞台,后期我们在说IO流是会详细介绍,这里就不介绍啦!我们可以看一下Hashtable存储null时抛出的空指针异常:

 /*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/ package cn.org.yinzhengjie.note3; import java.util.Hashtable;
import java.util.Map; public class HashtableDemo {
public static void main(String[] args) {
Map<String, String> map = new Hashtable<>();
map.put(null, null);
System.out.println(map);
}
} /*
以上代码执行结果如下:
Exception in thread "main" java.lang.NullPointerException
at java.base/java.util.Hashtable.put(Hashtable.java:475)
at cn.org.yinzhengjie.note3.HashtableDemo.main(HashtableDemo.java:15)
*/

八.TreeMap的特点

  基于树的Map,它的键唯一,并可以自动排序,根据使用的构造方法决定是使用元素本身可比性还是使用集合的可比性。

 /*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/ package cn.org.yinzhengjie.note3; import java.util.TreeMap; public class TreeMapDemo {
public static void main(String[] args) {
TreeMap<String, Integer> tree = new TreeMap<>();
tree.put("yinzhengjie", 20);
tree.put("尹正杰", 18);
tree.put("Zhengjie", 20);
tree.put("BigData", 2018);
System.out.println(tree);
}
} /*
以上代码执行结果如下:
{BigData=2018, Zhengjie=20, yinzhengjie=20, 尹正杰=18}
*/