/**
-
Map集合常用Api */ public class MapDemo1 {
public static void main(String[] args) {
//创建Map集合对象
Map<Integer,String> map = new HashMap<>();
//向Map集合中添加键值对
map.put(1,"田福军");
//在这里进行了自动装箱 map.put(2,"孙玉厚");
map.put(3,"田福堂");
//通过key获取value
String value = map.get(1);
System.out.println(value);
//获取所有的value Collection<String> values =map.values();
for(String s: values){
System.out.println("所有的value值"+s);
}
//获取键值对数量
System.out.println("键值对的数量:"+map.size());
//通过key删除
key-value map.remove(2);
System.out.println("键值对的数量:"+map.size());
//判断是否包含某个key
//contains 底层调用的是equals方法进行比较的,所以自定义的类型需要重写equals方法 重写equals方法比较的是内容
System.out.println(map.containsKey(4));//false
//判断是否包含某个value
System.out.println(map.containsValue("田福军"));//true
//清空map map.clear();
System.out.println("键值对的数量:"+map.size());//0
//判断是否为空
System.out.println(map.isEmpty());//true
}
}
遍历方式:
/** *HashMap方式测试类 */
public class MapDemo {
public static void main(String[] args) {
HashMap<Integer,String> map = new HashMap<>();
//添加键值对
map.put(1,"孙少平");
map.put(2,"孙少安");
map.put(3,"田晓霞");
map.put(4,"田润叶");
//获取指定key的值
System.out.println(map.get(2));
//获取所有的key Set<Integer> keys = map.keySet(); //使用getkey遍历map集合 for(Integer key:keys){ System.out.println("key="+key+" value="+map.get(key)); } //通过迭代器获取节点的键值对 Iterator<Integer> it = keys.iterator(); while (it.hasNext()){ Integer key = it.next(); String value = map.get(key); System.out.println("key="+key+" value="+value); } //获取map集合的entry,其中包含key和value Set<Map.Entry<Integer,String>> set = map.entrySet(); //使用foreach遍历Map集合 这种方式比较适合大数据量 for(Map.Entry<Integer,String> entry:set){ System.out.println("key="+entry.getKey()+" value"+entry.getValue()); } //使用迭代器遍历集合 Iterator<Map.Entry<Integer,String>> entryIterator = set.iterator(); while (entryIterator.hasNext()){ Map.Entry<Integer,String> Itentry = entryIterator.next(); System.out.println("key="+Itentry.getKey()+" value="+Itentry.getValue()); } //lamba表达式 map.forEach((key,value)->System.out.println("key="+key+" value="+value)); }
}