从零开始的Java知识
- 双列数据集合(Day1)
- Map
双列数据集合(Day1)
Map
注意点:
- Map一次加入一个key-value
- 一个key对应一个value
- key与key之间是不重复的
- key-value被称为键值对,键值对对象或者是entry对象
常用方法案例:
import java.util.HashMap;
import java.util.Map;public class MapTest {public static void main(String[] args) {Map<String,String> map = new HashMap<>();// 1.put(key,value) 加入或者修改一组键值对, 返回修改前的value值// 2.remove(key) 删除// 3.clear()// 4.containKey(key)// 5.containValue(value)// 6.isEmpty()// 7.size()String preValue = map.put("zhangsan","lisi");System.out.println(preValue);map.put("wangwu","laoliu");preValue = map.put("zhangsan","zhangsan");System.out.println(preValue);System.out.println("=======================");System.out.println(map);map.remove("wangwu");System.out.println(map);boolean containKey = map.containsKey("zhangsan");boolean containValue = map.containsValue("zhangsan");System.out.println("=======================");map.clear();System.out.println(map.size());System.out.println(map.isEmpty());System.out.println("=======================");System.out.println(containKey);System.out.println(containValue);}
}
遍历方式:
- 遍历Key获取Value值
- 遍历Key Value
- 通过Lambda表达式
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;public class MapTest {public static void main(String[] args) {Map<String, String> map = new HashMap<>();// 1.put(key,value) 加入或者修改一组键值对, 返回修改前的value值// 2.remove(key) 删除// 3.clear()// 4.containKey(key)// 5.containValue(value)// 6.isEmpty()// 7.size()String preValue = map.put("zhangsan", "lisi");map.put("wangwu", "laoliu");// 方式1Set<String> keys = map.keySet();// 方式1.1 迭代器Iterator<String> iterator = keys.iterator();while (iterator.hasNext()) {String key = iterator.next();System.out.println(key + "-" + map.get(key));}// 方式1.2 增强forfor (String key : keys) {System.out.println(key + ":" + map.get(key));}// 方式1.3 Lambda表达式keys.forEach(key -> System.out.println(key + ":" + map.get(key)));System.out.println("--------------------------------");// 方式2Set<Map.Entry<String, String>> entries = map.entrySet();// 方式2.1 迭代器Iterator<Map.Entry<String, String>> iterator1 = entries.iterator();while (iterator1.hasNext()) {// Entry是Map的内部接口Map.Entry<String, String> entry = iterator1.next();System.out.println(entry.getKey() + ":" + entry.getValue());}// 方式2.2 增强forfor (Map.Entry<String, String> entry : entries) {System.out.println(entry.getKey() + ":" + entry.getValue());}// 方式2.3 Lambda表达式entries.forEach(entry -> System.out.println(entry.getKey() + ":" + entry.getValue()));System.out.println("--------------------------------");// 方式3// 底层是遍历entrySet,向BiConsumer函数式接口的accept方法填充对应的key和valuemap.forEach((key, value) -> System.out.println(key + ":" + value));}
}