icecool09
icecool09

Reputation: 99

Remove empty / null element from List

Hello i have been trying to remove empty / null element from List , have tried multiple things . not sure if i am missing something.

    public String getString() {
    List<String> result = new ArrayList<>();

    List<String> string1 = getDateResult();
    List<String> string2 = getStringResult();
    List<String> string3 = getNumberResult();
    List<String> string4 = getBookResult();

    result.add(string1);
    result.add(string2);
    result.add(string3);
    result.add(string4);

    // below are the things I already tried doesnt work 
    result.removeIf(List::isEmpty);
    result.removeAll(Arrays.asList(null,""));

    return result;
    }

Example Input

2020-08-10 , Hello , , Book1 --> cant remove / delete the empty String.

Upvotes: 0

Views: 1488

Answers (2)

Amar Dev
Amar Dev

Reputation: 1479

If you want to add one list into another use the addAll(..) method.

This assumes that you don't get a null back as a result of any method that creates string1, string1 lists.

result.addAll(string1); result.addAll(string2); ...

As result is a List<String>, you can now use the removeIf method to remove any invalid strings from you result.

If you are open to using Apache utils you can use the StringUtils.isBlank(str)

Upvotes: 0

Ryuzaki L
Ryuzaki L

Reputation: 40048

If you want to remove null or empty List inside List List<List<String>>

result.removeIf(list->list==null || list.isEmpty());

or if you want to remove null or empty elements from inner lists

result.forEach(list->list.removeIf(ele->ele==null || ele.isEmpty()));

Upvotes: 2

Related Questions