在Java中,判断多个值是否都为空或都不为空可以通过多种方式实现。以下是几种常见的方法:
Stream
API(Java 8及以上版本)如果你使用的是Java 8或更高版本,可以使用Stream
API来简洁地判断多个值是否都为空或都不为空。
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
String str1 = null;
String str2 = "";
String str3 = "Hello";
boolean allNull = Stream.of(str1, str2, str3).allMatch(s -> s == null);
boolean allNonNull = Stream.of(str1, str2, str3).allMatch(s -> s != null);
System.out.println("All null: " + allNull); // 输出: All null: false
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 = null;
String str2 = "";
String str3 = "Hello";
boolean allNull = Objects.isNull(str1) && Objects.isNull(str2) && Objects.isNull(str3);
boolean allNonNull = Objects.nonNull(str1) && Objects.nonNull(str2) && Objects.nonNull(str3);
System.out.println("All null: " + allNull); // 输出: All null: false
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 = null;
String str2 = "";
String str3 = "Hello";
boolean allNull = Optional.ofNullable(str1).isEmpty() &&
Optional.ofNullable(str2).isEmpty() &&
Optional.ofNullable(str3).isEmpty();
boolean allNonNull = Optional.ofNullable(str1).isPresent() &&
Optional.ofNullable(str2).isPresent() &&
Optional.ofNullable(str3).isPresent();
System.out.println("All null: " + allNull); // 输出: All null: false
System.out.println("All non-null: " + allNonNull); // 输出: All non-null: false
}
}
如果你不想使用任何工具类或API,也可以手动进行判断。
public class Main {
public static void main(String[] args) {
String str1 = null;
String str2 = "";
String str3 = "Hello";
boolean allNull = (str1 == null) && (str2 == null) && (str3 == null);
boolean allNonNull = (str1 != null) && (str2 != null) && (str3 != null);
System.out.println("All null: " + allNull); // 输出: All null: false
System.out.println("All non-null: " + allNonNull); // 输出: All non-null: false
}
}
Stream
API:适用于Java 8及以上版本,代码简洁。Objects
工具类:适用于Java 7及以上版本,代码简洁且易读。Optional
类:适用于Java 8及以上版本,代码简洁且功能强大。根据你的需求和Java版本,选择最适合的方法即可。