Note/Map LIst String Object判空.md
2024-01-13 14:14:45 +08:00

71 lines
1.7 KiB
Markdown

Java 中的 Map List String Object 判空
## 1.Map
可使用工具包有 `CollectionUtils` `MapUtils`
### 返回一个空的`Map`
```java
// 输出1
public static void main(String[] args) {
HashMap<String, String> stringStringHashMap = new HashMap<>();
boolean empty = MapUtils.isEmpty(stringStringHashMap);
System.out.println(empty ? "1" : "0");
}
```
对于`Map`其中的数值为空则需要具体判断
```java
// 输出0
public static void main(String[] args) {
HashMap<String, String> stringStringHashMap = new HashMap<>();
stringStringHashMap.put("str",null);
boolean empty = MapUtils.isEmpty(stringStringHashMap);
System.out.println(empty ? "1" : "0");
}
```
```java
// 输出0
public static void main(String[] args) {
HashMap<String, String> stringStringHashMap = new HashMap<>();
stringStringHashMap.put("str", null);
boolean empty = MapUtils.isEmpty(stringStringHashMap);
String str = stringStringHashMap.get("str");
if (!empty && str != null) {
System.out.println("0");
} else {
System.out.println("1");
}
}
```
```java
// 输出1
public static void main(String[] args) {
HashMap<String, String> stringStringHashMap = new HashMap<>();
stringStringHashMap.put("st","");
boolean empty = MapUtils.isEmpty(stringStringHashMap);
String str = stringStringHashMap.get("str");
if (!empty && str != null) {
System.out.println("0");
} else {
System.out.println("1");
}
}
```
### 返回一个`Map`为空
```java
// 报空指针
public static void main(String[] args) {
HashMap<String, String> stringStringHashMap= null;
boolean empty = CollectionUtils.isEmpty(stringStringHashMap);
System.out.println(empty ? "1" : "0");
}
```