在Java中,判断多个值是否都为空或都不为空可以通过多种方式实现。以下是几种高效的方法:
Stream
API如果你有一组值,可以使用 Stream
API 来判断它们是否都为空或都不为空。
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
String str3 = null;
// 判断是否都为空
boolean allNull = Stream.of(str1, str2, str3).allMatch(s -> s == null);
System.out.println("All null: " + allNull); // 输出: All null: false
// 判断是否都不为空
boolean allNonNull = Stream.of(str1, str2, str3).allMatch(s -> s != null);
System.out.println("All non-null: " + allNonNull); // 输出: All non-null: false
}
}
Objects
工具类Objects
类提供了 isNull
和 nonNull
方法,可以简化判断。
import java.util.Objects;
public class Main {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
String str3 = null;
// 判断是否都为空
boolean allNull = Objects.isNull(str1) && Objects.isNull(str2) && Objects.isNull(str3);
System.out.println("All null: " + allNull); // 输出: All null: false
// 判断是否都不为空
boolean allNonNull = Objects.nonNull(str1) && Objects.nonNull(str2) && Objects.nonNull(str3);
System.out.println("All non-null: " + allNonNull); // 输出: All non-null: false
}
}
Optional
类Optional
类可以用于处理可能为空的值,并且可以链式调用。
import java.util.Optional;
public class Main {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
String str3 = null;
// 判断是否都为空
boolean allNull = Optional.ofNullable(str1).isEmpty() &&
Optional.ofNullable(str2).isEmpty() &&
Optional.ofNullable(str3).isEmpty();
System.out.println("All null: " + allNull); // 输出: All null: false
// 判断是否都不为空
boolean allNonNull = Optional.ofNullable(str1).isPresent() &&
Optional.ofNullable(str2).isPresent() &&
Optional.ofNullable(str3).isPresent();
System.out.println("All non-null: " + allNonNull); // 输出: All non-null: false
}
}
如果你需要频繁进行这种判断,可以封装一个自定义方法。
public class Main {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
String str3 = null;
// 判断是否都为空
boolean allNull = areAllNull(str1, str2, str3);
System.out.println("All null: " + allNull); // 输出: All null: false
// 判断是否都不为空
boolean allNonNull = areAllNonNull(str1, str2, str3);
System.out.println("All non-null: " + allNonNull); // 输出: All non-null: false
}
public static boolean areAllNull(Object... objects) {
for (Object obj : objects) {
if (obj != null) {
return false;
}
}
return true;
}
public static boolean areAllNonNull(Object... objects) {
for (Object obj : objects) {
if (obj == null) {
return false;
}
}
return true;
}
}
根据你的具体需求选择合适的方法即可。