map非空判断 java
时间: 2024-01-11 22:18:45 浏览: 40
在Java中,可以使用以下方式判断Map是否为空:
1. 使用isEmpty()方法判断Map是否为空,如果为空则返回true,否则返回false。
```java
Map<String, String> map = new HashMap<>();
if (map.isEmpty()) {
System.out.println("Map is empty");
} else {
System.out.println("Map is not empty");
}
```
2. 使用size()方法判断Map的大小是否为0,如果为0则说明Map为空。
```java
Map<String, String> map = new HashMap<>();
if (map.size() == 0) {
System.out.println("Map is empty");
} else {
System.out.println("Map is not empty");
}
```
3. 使用Map的keySet()方法获取Map中所有的key,然后判断key的数量是否为0,如果为0则说明Map为空。
```java
Map<String, String> map = new HashMap<>();
if (map.keySet().size() == 0) {
System.out.println("Map is empty");
} else {
System.out.println("Map is not empty");
}
```