import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
public class demo {
public static void main(String[] args) {
//创建双列Map集合
Map<String,String> m=new HashMap<>();
//添加元素
m.put("ppp","aaa");
m.put("老刘","老七");
m.put("小米","华为");
//通过键找值
//把所有键给提出到单列集合中
Set<String> keys = m.keySet();
/*
//遍历单列集合 增强for
for (String key : keys) {
//利用map的键去获取对应的值 get
String value = m.get(key);
System.out.println(key+"="+value);
}
//利用迭代器iterator 来遍历
Iterator<String> it = keys.iterator();
while (it.hasNext()){
String key = it.next();
//利用map的键去获取对应的值 get
String value = m.get(key);
System.out.println(key+"="+value);
}
*/
//用lambad遍历 foreach
keys.forEach(new Consumer<String>() {
@Override
public void accept(String key) {
利用map的键去获取对应的值 get
String value = m.get(key);
System.out.println(key+"="+value);
}
});
}
}
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
public class demo {
public static void main(String[] args) {
//创建map集合
Map<String,String>m=new HashMap<>();
//创建元素
m.put("老刘","老六");
m.put("小刘","小六");
m.put("老q","老k");
//Map集合第二种遍历方式 键值对对象进行遍历
//通过一个方法获取所有键值对对象 返回一个set集合
Set<Map.Entry<String, String>> entries = m.entrySet();
/*
//for增强遍历 遍历entries 获取里面每个键值对
for (Map.Entry<String, String> entry : entries) {
//利用entry调用get 获取键和值
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key+"="+value);
}
//迭代器iterator 遍历
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);
}
*/
//lambda遍历
entries.forEach(new Consumer<Map.Entry<String, String>>() {
@Override
public void accept(Map.Entry<String, String> s) {
String key = s.getKey();
String value = s.getValue();
System.out.println(key+"="+value);
}
});
}
}
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;
public class demo {
public static void main(String[] args) {
//创建map集合
Map<String,String> m=new HashMap<>();
//添加元素
m.put("p","q");
m.put("pk","l");
m.put("人","物");
m.put("a","k");
//map第三种遍历方式 lambda
m.forEach(( key, value)-> System.out.println(key+"="+value));
}
}