【问题标题】:How to check a List whether it contains all the elements as NULL string?如何检查列表是否包含所有元素作为 NULL 字符串?
【发布时间】:2014-02-06 02:24:56
【问题描述】:

我有一个 LinkedList 作为 -

List<String> tables = new LinkedList<String>();

有时,tables 列表看起来像,这意味着其中包含所有空字符串值 -

[null, null]

是否有任何直接的方法可以识别tables列表中的所有元素是否为null字符串,则返回true,否则返回false。

我能想到的一种方法就是继续迭代它,看看它是否有空字符串,然后相应地返回真或假。

更新:-

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;
}

【问题讨论】:

  • 你认为正确的方式。

标签: java list linked-list


【解决方案1】:

如果你可以使用 Guava 库:

Iterables.all(input, Predicates.isNull());

使用static import,它将变得更加可读:

import static com.google.common.base.Predicates.isNull;
import static com.google.common.collect.Iterables.all;

Iterable<?> input = ...
all(input, isNull())

【讨论】:

    【解决方案2】:

    是的,您的想法很好,如果您将其作为实用程序类的一部分会更好

    public static boolean isAllNull(Iterable<?> list){
        for(Object obj : list){
            if(obj != null)
                return false;
        }
    
        return true;
    }
    

    请注意,此实用程序接受Iterable 接口,以便在更广泛的范围内工作。

    【讨论】:

    • 拥有 Iterable 有什么好处> 还是我们不应该传递 List 并对其进行迭代?
    • 是的,使用Iterable 代替List 接口将使此实用程序方法与SetQueueStack 等类型的其他Iterable 实现一起使用。 util 所以更好地最大化多态性。
    • 酷。谢谢小费。我已经更新了我的问题。你能检查一下我的做法是否正确吗?只需要第二只眼睛..
    • 是的,它是正确的。在您提供的代码中,它将返回 false,因为 table_2 不是 null。如果您将table_2 设置为null,那么它将返回true。
    【解决方案3】:

    你是对的,这就是解决方案。您可以检查是否有任何非 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");}
    }
    

    【讨论】:

      【解决方案4】:

      没有 3rd 方库:

      Set set = new HashSet(tables);
      boolean allNull = set.size() == 1 && set.iterator().next() == null;
      

      【讨论】:

        猜你喜欢
        • 2017-11-20
        • 1970-01-01
        • 2010-10-04
        • 1970-01-01
        • 1970-01-01
        • 2013-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多