[英]How to check a List whether it contains all the elements as NULL string?
I am having a LinkedList
as - 我有一个
LinkedList
作为 -
List<String> tables = new LinkedList<String>();
Sometimes, tables
list will look like, meaning it will have all the null string values inside it - 有时,
tables
列表看起来像,意味着它将包含所有空字符串值 -
[null, null]
Is there any direct way of identifying if the tables
list has all the elements as null
string, then return true, otherwise return false. 有没有直接的方法来识别
tables
列表是否所有元素都为null
字符串,然后返回true,否则返回false。
One way I can think of is just keep on iterating it and see whether it has null string or not and then return true or false accordingly. 我能想到的一种方法就是继续迭代它,看它是否有空字符串,然后相应地返回true或false。
UPDATE:- 更新: -
public static void main(String[] args) {
String table_1 = null;
String table_2 = "hello";
List<String> tables = new LinkedList<String>();
tables.add(table_1);
tables.add(table_2);
boolean ss = isAllNull(tables);
System.out.println(ss);
}
public static boolean isAllNull(Iterable<?> list) {
for (Object obj : list) {
if (obj != null)
return false;
}
return true;
}
If you can use Guava library: 如果你可以使用Guava库:
Iterables.all(input, Predicates.isNull());
With static import
it will become even more readable: 使用
static import
,它将变得更具可读性:
import static com.google.common.base.Predicates.isNull;
import static com.google.common.collect.Iterables.all;
Iterable<?> input = ...
all(input, isNull())
Yes what you are thinking is good, better if you make it as part of your utility class 是的,你认为是好的,如果你把它作为你的实用工具类的一部分更好
public static boolean isAllNull(Iterable<?> list){
for(Object obj : list){
if(obj != null)
return false;
}
return true;
}
Note that this util accepts Iterable
interface for it to work in a wider scope. 请注意,此util接受
Iterable
接口,以便在更广泛的范围内工作。
You were correct that is the solution. 你说的是正确的解决方案。 You can check if there is any not null and return false at the first occurrence.
您可以检查是否存在任何非null并在第一次出现时返回false。
String table_1 = null;
String table_2 = null;
List<String> tables = new LinkedList<>();
tables.add(table_1);
tables.add(table_2);
for (String table : tables) {
if (table != null)
{System.out.println("False");}
}
Without 3rd party libraries: 没有第三方库:
Set set = new HashSet(tables);
boolean allNull = set.size() == 1 && set.iterator().next() == null;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.