Java 如何检查字符串数组中的元素是否为空?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19801152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if an element in a string array is empty?
提问by Jakub Pomyka?a
How can I check if an element in a string array is empty? This is my example array:
如何检查字符串数组中的元素是否为空?这是我的示例数组:
private static String correct[] = new String[5];
static {
correct[1] = "some texT";
correct[2] = "some texT3";
correct[4] = "some texT2";
}
I can assign null
to rest of elements, but I want to find another, better way to do this.
I found isEmpty
, but it is available only on API 9 and above.
我可以分配null
给其余的元素,但我想找到另一种更好的方法来做到这一点。我找到了isEmpty
,但它仅适用于 API 9 及更高版本。
if(correct[0].length() > 0)
gives me a NPE.
if(correct[0] != null
also.
if(correct[0].length() > 0)
给我一个 NPE。
if(correct[0] != null
还。
采纳答案by rolfl
Have you tried the 'obvious':
您是否尝试过“显而易见”:
if(correct[0] != null && correct[0].length() > 0) {
//it is not null and it is not empty
}
回答by rgettman
Just compare it to null
, which is the default value for an array of some object type.
只需将它与 比较null
,这是某种对象类型数组的默认值。
if (correct[0] != null && correct[0].length() > 0)
The &&
operator will only evaluate the right side if the left side is true
, i.e. correct[0]
isn't null
and won't throw a NullPointerException
.
该&&
运营商将仅分析右边如果左边是true
,即correct[0]
是不是null
,也不会抛出NullPointerException
。
回答by Mike
Well if you can't use isEmpty try to use Array.Contains(null) or try this small loop
那么如果你不能使用 isEmpty 尝试使用 Array.Contains(null) 或尝试这个小循环
for(int i = 0;i<=Array.length;i++){
if(array[i] > 0 && array[i] != null){
//yay its not null
}
}
回答by bosco
If you're trying to check if a specific element in a specific position is empty (not only different from null
, but from ""
too), the presented solutions won't be enough.
如果您试图检查特定位置的特定元素是否为空(不仅与 不同null
,而且来自""
),所提供的解决方案是不够的。
Java has a lot of ways to do this. Let's see some of them:
Java 有很多方法可以做到这一点。让我们看看其中的一些:
You can convert your array into a
List
(usingArrays's asList
method) and check the conditions throughcontains()
method:import java.util.*; public class Test1 { private static boolean method1_UsingArrays(String[] array) { return Arrays.asList(array).contains(null) || Arrays.asList(array).contains(""); } }
It's also possible to use
Collections's disjoint
method, to check whether two collections have elements in common or not:import java.util.*; public class Test2 { private static String[] nullAndEmpty = {"", null}; private static boolean method2_UsingCollectionsDisjoint(String[] array) { // disjoint returns true if the two specified collections have no elements in common. return !Collections.disjoint( // Arrays.asList(array), // Arrays.asList(nullAndEmpty) // ); } }
If you're able to use Java 8(my favorite option), it's possible to make use of the new Streams API.
import java.util.stream.*; import java.util.*; public class Test3 { private static boolean method3_UsingJava8Streams(String[] array) { return Stream.of(array).anyMatch(x -> x == null || "".equals(x)); } }
Compared to the other options, this is even easier to handle in case you need to
trim
each of your strings (or call any of the otherString
's methods):Stream.of(array).anyMatch(x -> x == null || "".equals(x.trim()));
您可以将数组转换为
List
(使用Arrays's asList
方法)并通过contains()
方法检查条件:import java.util.*; public class Test1 { private static boolean method1_UsingArrays(String[] array) { return Arrays.asList(array).contains(null) || Arrays.asList(array).contains(""); } }
也可以使用
Collections's disjoint
方法来检查两个集合是否有共同的元素:import java.util.*; public class Test2 { private static String[] nullAndEmpty = {"", null}; private static boolean method2_UsingCollectionsDisjoint(String[] array) { // disjoint returns true if the two specified collections have no elements in common. return !Collections.disjoint( // Arrays.asList(array), // Arrays.asList(nullAndEmpty) // ); } }
如果您能够使用Java 8(我最喜欢的选项),则可以使用新的Streams API。
import java.util.stream.*; import java.util.*; public class Test3 { private static boolean method3_UsingJava8Streams(String[] array) { return Stream.of(array).anyMatch(x -> x == null || "".equals(x)); } }
与其他选项相比,这更容易处理,以防您需要
trim
每个字符串(或调用其他任何String
方法):Stream.of(array).anyMatch(x -> x == null || "".equals(x.trim()));
Then, you can easily call and test them:
然后,您可以轻松调用并测试它们:
public static void main(String[] args) {
// Ok tests
String[] ok = {"a", "b", "c"};
System.out.println("Method 1 (Arrays - contains): " + method1_UsingArrays(ok)); // false
System.out.println("Method 2 (Disjoint): " + method2_UsingCollectionsDisjoint(ok)); // false
System.out.println("Method 3 (Java 8 Streams): " + method3_UsingJava8Streams(ok)); // false
System.out.println("-------------------------------");
// Nok tests
String[] nok = {"a", null, "c"};
System.out.println("Method 1 (Arrays - contains): " + method1_UsingArrays(nok)); // true
System.out.println("Method 2 (Disjoint): " + method2_UsingCollectionsDisjoint(nok)); // true
System.out.println("Method 3 (Java 8 Streams): " + method3_UsingJava8Streams(nok)); // true
// Nok tests
String[] nok2 = {"a", "", "c"};
System.out.println("Method 1 (Arrays - contains): " + method1_UsingArrays(nok2)); // true
System.out.println("Method 2 (Disjoint): " + method2_UsingCollectionsDisjoint(nok2)); // true
System.out.println("Method 3 (Java 8 Streams): " + method3_UsingJava8Streams(nok2)); // true
}
回答by Mircea Stanciu
Had similar version where number of arguments could be bigger
有类似的版本,其中参数的数量可能更大
if (Arrays.asList(new String[] {productId, productTitle, imageName, productPrice}).contains(null)) {
return null;
}
回答by Woojin Ahn
Just Use isAnyEmpty
只需使用 isAnyEmpty
org.apache.commons.lang3
StringUtils.isAnyEmpty(final CharSequence... css)