package demo.assemble;
import org.junit.Test;
import java.util.*;
//key值 是无序,不重复的
public class 集合框架_Map基本方法和遍历 {
//基本方法演示
@Test
public void demo() {
Map<Integer, String> m = new HashMap<>();
m.put(1, "a");
m.put(2, "b");
System.out.println(m.put(3, "c"));//null 返回与键相关联的旧值
System.out.println(m.put(3, "d"));//c
System.out.println("打印:" + m);//{1=a, 2=b, 3=d}
System.out.println("长度:" + m.size());//3
System.out.println("是否为空:" + m.isEmpty());//false
System.out.println("删除:" + m.remove(3));//d 返回其值
System.out.println("删除后:" + m);//{1=a, 2=b}
System.out.println("是否包含指定键:" + m.containsKey(1));//true
System.out.println("是否包含指定值:" + m.containsKey(2));//true
System.out.println("获取指定键的值:" + m.get(1));//a 没有返回null
}
//遍历map 利用ketSet方法
@Test
public void traverseMap() {
Map<Integer, String> m = new HashMap<>();
m.put(3, "c");
m.put(2, "b");
m.put(1, "a");
Set<Integer> s = m.keySet();//将map中键key集合全部给Set集合的对象keySet
Iterator<Integer> it = s.iterator();//构建一个set集合的迭代器
while (it.hasNext()) {//使用set迭代器迭代key
Integer key = it.next();
String value = m.get(key);
System.out.println(key + ":" + value);
}
}
//遍历map 利用entrySet()方法
@Test
public void traverseMap2() {
Map<Integer, String> m = new HashMap<>();
m.put(3, "c");
m.put(2, "b");
m.put(1, "a");
Set<Map.Entry<Integer, String>> s = m.entrySet();//将键值关系存入Set集合 键唯一
Iterator<Map.Entry<Integer, String>> it = s.iterator();//构建一个set集合的迭代器
// Iterator<Map.Entry<Integer,String>> it = m.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> me = it.next();
//me.getKey();
//me.getValue();
System.out.println(me);
}
}
//遍历map中的value值
@Test
public void traverseMapValue() {
Map<Integer, String> m = new HashMap<>();
m.put(3, "c");
m.put(2, "b");
m.put(1, "a");
Collection<String> coll = m.values();//将值关系存入集合 值不唯一 无需Set集合
Iterator<String> it = coll.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
/**
* Map常用的子类:
* |--Hashtable :内部结构是哈希表,是同步的。不允许null作为键,null作为值。
* |--Properties:用来存储键值对型的配置文件的信息,可以和IO技术相结合。
* |--HashMap : 内部结构是哈希表,不是同步的。允许null作为键,null作为值。
* |--TreeMap : 内部结构是二叉树,不是同步的。可以对Map集合中的键进行排序。
*/
集合框架Map的基本方法和常用遍历方式
最新推荐文章于 2023-11-28 11:27:50 发布