MAP遍历方式
1.键找值 keySet()
点击查看代码
public class MapDemo2 {
public static void main(String[] args) {
//Map集合中的第一种遍历方式
//键找值
Map<String, String> m = new HashMap<>();
m.put("神原秋人", "栗山未来");
m.put("夏目贵志", "斑");
m.put("平泽唯", "中野梓");
//通过键找值
//获取所有的键,存到单列集合中
Set<String> keys = m.keySet();
//遍历单列集合,得到每一个键
//增强for
for (String key : keys) {
//利用m集合中的键获取对应的值
String value = m.get(key);
System.out.println(key + " = " + value);
}
System.out.println("---------------------------------------");
//迭代器
Iterator<String> it = keys.iterator();
while (it.hasNext()) {
String key = it.next();
String value = m.get(key);
System.out.println(key + " = " + value);
}
System.out.println("---------------------------------------");
//lambda表达式
keys.forEach(key -> {
String value = m.get(key);
System.out.println(key + " = " + value);
}
);
}
}
2.通过键值对对象遍历
点击查看代码
public class MapDemo3 {
public static void main(String[] args) {
//第二种遍历方式
Map<String, String> map = new HashMap<>();
map.put("神原秋人", "栗山未来");
map.put("夏目贵志", "斑");
map.put("平泽唯", "中野梓");
//通过一个方法获取所有键值对对象,返回一个Set集合
Set<Map.Entry<String, String>> entries = map.entrySet();
//遍历entries集合,得到每一个键值对对象
//利用entry调用getKey、getValue获取键和值
//增强for
for (Map.Entry<String, String> entry : entries) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + " = " + value);
}
System.out.println("---------------------------------------");
//迭代器
Iterator<Map.Entry<String, String>> it = entries.iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + " = " + value);
}
System.out.println("---------------------------------------");
//lambda表达式
entries.forEach(entry -> {
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + " = " + value);
}
);
}
}
3.Lambda表达式遍历
点击查看代码
public class MapDemo4 {
public static void main(String[] args) {
//第三种遍历方式
Map<String, String> map = new HashMap<>();
map.put("神原秋人", "栗山未来");
map.put("夏目贵志", "斑");
map.put("平泽唯", "中野梓");
//利用lambda表达式进行遍历
//底层:
//forEach其实就是利用第二种方式进行遍历,依次得到每一个键和值
//再调用accept方法
map.forEach(new BiConsumer<String, String>() {
@Override
public void accept(String key, String value) {
System.out.println(key + " = " + value);
}
});
//简化
//map.forEach((key, value) -> System.out.println(key + " = " + value));
}
}

浙公网安备 33010602011771号