Map集合
特点
- 保存键和值
- 键不能重复
- 一个键对应一个值
有对应关系的就考虑使用Map来存储
代码实例
public static void main(String[] args) {
HashMap<Integer,String> hs = new HashMap<>();
hs.put(1,"xiaohong");//put---添加/修改
hs.put(2,"xiaohuang");
hs.put(3,"xiaohei");
hs.put(4,"xiaobai");
hs.put(5,"xiaolv");
hs.put(6,"xiaohei");//当没有重复的键时,添加键值对并返回null;
hs.put(1,"xiaolan");//当有重复的键时,会进行修改操作,并返回被修改的值
System.out.println(hs);
System.out.println(hs.get(1));//xiaolan 通过键来获取对应的值
hs.remove(2);//删除键为2的xiaohuang键值对
System.out.println(hs);//{1=xiaolan, 3=xiaohei, 4=xiaobai, 5=xiaolv, 6=xiaohei}
System.out.println(hs.size());//5 获取map中的键值对个数
}
Map的遍历
Map遍历就是依次取出每个键和值(一次获取一对)
代码实例
通过键找值
public static void main(String[] args) {
HashMap<Integer,String> hs = new HashMap<>();
hs.put(1,"xiaohong");//put---添加/修改
hs.put(2,"xiaohuang");
hs.put(3,"xiaohei");
hs.put(4,"xiaobai");
hs.put(5,"xiaolv");
hs.put(6,"xiaohei");//当没有重复的键时,添加键值对并返回null;
Set<Integer> key = hs.keySet();
for (Integer i : key) {
System.out.println(hs.get(i));
}
}
Entry键值对遍历
是一个接口,表示键值对对象,里面会保存键和值,Entry相当于结婚证
遍历步骤
1.得到所有的Entry
2.遍历得到每个Entry
3.通过Entry得到键和值
代码实例
public static void main(String[] args) {
HashMap<Integer, String> hs = new HashMap<>();
hs.put(1, "xiaohong");//put---添加/修改
hs.put(2, "xiaohuang");
hs.put(3, "xiaohei");
hs.put(4, "xiaobai");
hs.put(5, "xiaolv");
hs.put(6, "xiaohei");//当没有重复的键时,添加键值对并返回null;
Set<Map.Entry<Integer, String>> se = hs.entrySet();
// System.out.println(se);
for (Map.Entry<Integer, String> i : se) {
System.out.println(i.getKey() +"------"+i.getValue());
//getKey()获取键
//getValue()获取值
}
}