Map集合
笔记
Map
Map 使用迭代器
- 使用
map.keySet()
获得键的视图,或者map.keySet().iterator()
直接获得迭代器 - 使用
迭代器.next()
拿到键 key - 使用
map.getKey(key)
获得键值 value 可以输出键值 value 了 具体代码如下: Map 初始化:
Map<String,ArrayList<Student>> map = new HashMap<>(); ArrayList<Student> list1 = new ArrayList<>(); ArrayList<Student> list2 = new ArrayList<>(); list1.add(new Student("zhang3","10000")); list1.add(new Student("li4","10001")); list2.add(new Student("zhao4","10002")); list2.add(new Student("liuneng","10003")); map.put("长沙", list1); map.put("东北", list2);
使用迭代器迭代打印:
Iterator<String> i = map.keySet().iterator();
while(i.hasNext()) {
String key = i.next();
ArrayList<Student> stu = map.get(key);
System.out.println(key);
for(int j = 0; j < stu.size(); j ++) {
System.out.println(stu.get(j));
}
}
Map 这个集合,嵌套使用起来的话是比较复杂的,有时候会把自己搞晕了。因此,搞明白其存储原理和读取原理是很重要的,再有就是要明白 Map 中各种函数的用法,这样就不会糊涂了!
Entry 键值对对象迭代 Map
Map 中存放的是两种对象,一种称为 key(键),一种称为 value(值),它们在在 Map 中是一一对应关 系,这一对对象又称做 Map 中的一个 Entry(项) 。Entry将键值对的对应关系封装成了对象。即键值 对对象,这样我们在遍历 Map 集合时,就可以从每一个键值对( Entry )对象中获取对应的键与对 应的值。在 Map集合中也提供了获取所有 Entry 对象的方法:
- public Set
> entrySet() : 获取到 Map 集合中所有的键值对对象的集合(Set 集合)。 - public K getKey() :获取 Entry 对象中的键。
public V getValue() :获取 Entry 对象中的值。 那么也可以使用 Entry 来迭代打印 Map,这里 Map 依旧使用上面提到的初始化内容: 代码:
//使用 Entry 获取键对 Iterator<Entry<String,ArrayList<Student>>> it = map.entrySet().iterator(); while(it.hasNext()) { Entry<String,ArrayList<Student>> entry = it.next(); System.out.println(entry.getKey()); for(Student s : entry.getValue()) { System.out.println(s); } }
等待更新……