Map
public class MapDemo1 {
public static void main(String[] args) {
/*
V put(K key, V value)//添加元素
V remove(Object key)//根据键删除键值对元素
void clear()//移除所有的键值对元素
boolean containsKey(Object key)//判断集合是否包含指定的键
boolean containsValue(Object value)//判断集合是否包含指定的值
boolean isEmpty()//判断集合是否为空
int size()//集合的长度,也就是集合中键值对的个数
*/
//创建集合对象
Map<String,String> map=new HashMap<>();
//1.添加元素
//put方法的细节:
//添加/覆盖
//添加数据时如果键不存在,则直接添加键值对,并返回null
//添加数据时如果键存在,则覆盖原来的键值对,并返回原来的值
String value1=map.put("zhangsan","1");
map.put("lisi","2");
map.put("wangwu","3");
String value2=map.put("zhangsan","4");
System.out.println(value1);//null
System.out.println(value2);//1
System.out.println(map);//{lisi=2, zhangsan=4, wangwu=3}
//2.删除元素
String s1=map.remove("zhangsan");
System.out.println(s1);//4
System.out.println(map);//{lisi=2, wangwu=3}
//3.清空
//map.clear();
//4,5.判断是否包含
boolean keyResult=map.containsKey("lisi");
boolean valueResult=map.containsValue("3");
System.out.println(keyResult);//true
System.out.println(valueResult);//true
//6.判空
boolean flag=map.isEmpty();
System.out.println(flag);//false
//7.长度
int size=map.size();
System.out.println(size);//2
}
}
-----------------------------------------------
public class MapDemo2 {
public static void main(String[] args) {
//遍历
Map<String,String> map=new HashMap<>();
map.put("zhangsan","1");
map.put("lisi","2");
map.put("wangwu","3");
//1.键找值
//获取所有的键,并且放到一个单列集合中,再用get方法获得值
Set<String> set = map.keySet();
for (String s : set) {
System.out.println(s+"="+map.get(s));
}
System.out.println("-------------");
Iterator<String> it = set.iterator();
while(it.hasNext()){
String key = it.next();
System.out.println(key+"="+map.get(key));
}
System.out.println("-------------");
set.forEach(key-> System.out.println(key+"="+map.get(key)));
System.out.println("-------------");
//2.键值对
//通过方法获取所有的键值对,并且返回一个set集合
Set<Map.Entry<String, String>> set1 = map.entrySet();
for(Map.Entry<String, String> entry:set1){
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key+"="+value);
}
System.out.println("-------------");
Iterator<Map.Entry<String, String>> it2 = set1.iterator();
while(it2.hasNext()){
Map.Entry<String, String> entry = it2.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key+"="+value);
}
System.out.println("-------------");
set1.forEach(entry-> System.out.println(entry.getKey()+"="+entry.getValue()));
System.out.println("-------------");
//3.lambda表达式
map.forEach(new BiConsumer<String, String>() {
@Override
public void accept(String key, String value) {
System.out.println(key+"="+value);
}
});
System.out.println("-------------");
//简化
map.forEach((key,value)-> System.out.println(key+"="+value));
}
}
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 Hexo!