1.存储时以键值对存储
2取值时可以根据键获取对应的值
3.键不能重复,如果重复了,旧值会被新值覆盖4.值可以重复
HashMap
LinkedHashMap
TreeMap
public static void main(String[] args) {Map map = new HashMap<>();map.put("你好","hello");map.put("世界","word");System.out.println(map);Map map2 = new HashMap<>();map2.put("name","map2");map2.putAll(map);System.out.println(map2);}
输出结果如下:
{你好=hello, 世界=word}
{你好=hello, name=map2, 世界=word}
不难看出我们使用的HashMap是无序的
这个我们后边会讲到
Map map = new HashMap<>();map.put("你好","hello");map.put("世界","word");map.put("我","i");map.put("是","am");map.put("中国人", "Chinese");System.out.println("这是删除之前的map>>>>>>>" + map);String val = map.remove("你好");System.out.println("这是删除之后的map>>>>>>>" + map);System.out.println("删除的值是:"+val);
这是删除之前的map>>>>>>>{我=i, 你好=hello, 中国人=Chinese, 世界=word, 是=am}
这是删除之后的map>>>>>>>{我=i, 中国人=Chinese, 世界=word, 是=am}
删除的值是:hello
jdk1.8新增的功能Set keySet() 返回map集合中所有的key 存储到Set集合Collection values() 返回map集合中所有的value 存储到Collecton集合 public static void main(String[] args) {Map map = new HashMap<>();map.put("你好","hello");map.put("世界","word");map.put("我","i");map.put("是","am");map.put("中国人", "Chinese");System.out.println("这是删除之前的map>>>>>>>" + map);String val = map.remove("你好");System.out.println("这是删除之后的map>>>>>>>" + map);System.out.println("删除的值是:"+val);map.replace("我","me");System.out.println("这是替换之后的map>>>>>>>>>>>"+ map);System.out.println("集合中是否包含键’我‘:" +map.containsKey("我"));System.out.println("集合中是否包含值’word‘:" +map.containsValue("word"));System.out.println("集合中所有的key:"+ map.keySet());System.out.println("集合中所有的value:"+ map.values());System.out.println("获取集合中所有的键值对"+map.entrySet());Set> entries = map.entrySet();for (Map.Entry entry :entries) {System.out.println("键:"+entry.getKey()+" 值"+entry.getValue());}}
运行结果如下:
这是删除之前的map>>>>>>>{我=i, 你好=hello, 中国人=Chinese, 世界=word, 是=am}
这是删除之后的map>>>>>>>{我=i, 中国人=Chinese, 世界=word, 是=am}
删除的值是:hello
这是替换之后的map>>>>>>>>>>>{我=me, 中国人=Chinese, 世界=word, 是=am}
集合中是否包含键’我‘:true
集合中是否包含值’word‘:true
集合中所有的key:[我, 中国人, 世界, 是]
集合中所有的value:[me, Chinese, word, am]
获取集合中所有的键值对[我=me, 中国人=Chinese, 世界=word, 是=am]
键:我 值me
键:中国人 值Chinese
键:世界 值word
键:是 值am
System.out.println("map循环方法1");for (Map.Entry entry :entries) {System.out.println("键:"+entry.getKey()+" 值"+entry.getValue());}Set stringSet = map.keySet();System.out.println("map循环方法2");for (String s : stringSet) {String s1 = map.get(s);System.out.println("键:"+s + "值:" + s1);}
map循环方法1
键:我 值me
键:中国人 值Chinese
键:世界 值word
键:是 值am
map循环方法2
键:我值:me
键:中国人值:Chinese
键:世界值:word
键:是值:am
上一篇:2022美亚个人赛复盘