1 插入数据
1.1 插入null键
@Test
public void mapPutNullKeyTest() {
Map map = new HashMap<>();
map.put(null, "test1");
String value = map.get(null);
logger.info(">>>>>>>>>Value:" + value);
}
1.2 插入null值
@Test
public void mapPutNullValueTest() {
Map map = new HashMap<>();
map.put("2", null);
String value1 = map.get("2");
logger.info(">>>>>>>>>Value:" + value1);
}
2 查询数据
2.1 查询null键
@Test
public void mapKeyNullTest() {
Map map = new HashMap<>();
map.put("1", "test1");
map.put("2", "test2");
String value = map.get(null);
logger.info(">>>>>>>>>Value:" + value);
}
2.3 查询不存在的键
@Test
public void mapReturnNullTest() {
Map map = new HashMap<>();
map.put("1", "test1");
map.put("2", "test2");
String value = map.get("3");
logger.info(">>>>>>>>>Float:" + value);
}
2.4 查询第一条数据
@Test
public void mapFindFirstTest() {
Map map = new HashMap<>();
map.put("1", "test1");
map.put("2", "test2");
Optional> firstElement = map.entrySet().stream().findFirst();
firstElement.ifPresent(s -> logger.info(">>>>>>>>>Element:" + s));
firstElement.ifPresent(s -> logger.info(">>>>>>>>>key:" + s.getKey() + ", value:" + s.getValue()));
}
3 小结
| 序号 | 描述 |
|---|
| 1 | HashMap键可以为null |
| 2 | HashMap值可以为null |
| 3 | HashMap使用null作为键查询时,不会抛异常 |
4 完整样例
package com.monkey.java_study.functiontest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class MapTest {
private static final Logger logger = LogManager.getLogger(MapTest.class);
@Test
public void mapPutNullKeyTest() {
Map map = new HashMap<>();
map.put(null, "test1");
String value = map.get(null);
logger.info(">>>>>>>>>Value:" + value);
}
@Test
public void mapPutNullValueTest() {
Map map = new HashMap<>();
map.put("2", null);
String value1 = map.get("2");
logger.info(">>>>>>>>>Value:" + value1);
}
@Test
public void mapReturnNullTest() {
Map map = new HashMap<>();
map.put("1", "test1");
map.put("2", "test2");
String value = map.get("3");
logger.info(">>>>>>>>>Value:" + value);
}
@Test
public void mapKeyNullTest() {
Map map = new HashMap<>();
map.put("1", "test1");
map.put("2", "test2");
String value = map.get(null);
logger.info(">>>>>>>>>Value:" + value);
}
@Test
public void mapFindFirstTest() {
Map map = new HashMap<>();
map.put("1", "test1");
map.put("2", "test2");
Optional> firstElement = map.entrySet().stream().findFirst();
firstElement.ifPresent(s -> logger.info(">>>>>>>>>Element:" + s));
firstElement.ifPresent(s -> logger.info(">>>>>>>>>key:" + s.getKey() + ", value:" + s.getValue()));
}
}