user2467545
user2467545

Reputation:

How to check a List whether it contains all the elements as NULL string?

I am having a LinkedList as -

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

Sometimes, tables list will look like, meaning it will have all the null string values inside it -

[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.

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.

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

Upvotes: 3

Views: 9313

Answers (4)

Lluis Martinez
Lluis Martinez

Reputation: 1973

Without 3rd party libraries:

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

Upvotes: 0

Mauro Bellati
Mauro Bellati

Reputation: 29

If you can use Guava library:

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

With static import it will become even more readable:

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

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

Upvotes: 2

Bnrdo
Bnrdo

Reputation: 5474

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.

Upvotes: 1

sandiego
sandiego

Reputation: 161

You were correct that is the solution. You can check if there is any not null and return false at the first occurrence.

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

Upvotes: 0

Related Questions