Noufal Panolan
Noufal Panolan

Reputation: 1367

Remove null elements from list

List<String> list = new ArrayList<String>();
  list.add("One");
  list.add(null);
  list.add("Two!");
  list.add(null);
  list.add("Three");
  list.add(null);
  list.add("Four");
  list.add(null);

I have a list containing null elements. Is there any way to remove the null elements from the current collection without using any iterations?

Upvotes: 28

Views: 36472

Answers (10)

reubennn
reubennn

Reputation: 480

You could use a Java Stream to filter out the nullable elements:

list.stream()
    .filter(Objects::nonNull)
    .collect(Collectors.toList())

Upvotes: 0

Nikolas
Nikolas

Reputation: 44496

The current answers don't distinguish the mutable and immutable lists and I find a lot of ways missing. This becomes even more important with List.of(..) introduced as of , although one cannot pass a null element to it. The removal is relevant anyway (ex. removing a certain non-null element).

Immutable List

An example of a immutable list is Arrays.asList(..) (yet the elements can still be replaced, but not added/removed) or already mentioned List.of(..). These are considered as "immutable wrappers" as long as one cannot add/remove an element using the List methods.

List<String> immutableList = Arrays.asList("one", null, "two");
  • as of using the Stream#filter(Predicate) method:

    List<String> newList = immutableList.stream()
        .filter(Objects::nonNull)
        .collect(Collectors.toList());
    
  • For-each loop either with indices or the enhanced one is suitable (not only) for Java versions and lower.

    // note we need to create a mutable List to add the non-null elements
    List<String> newList = new ArrayList<>();
    for (String str: immutableList) {
        if (str != null) {
             newList.add(str);
        }
    }
    

Mutable List

An example of a mutable list is a new instance of the List interface such as new ArrayList<>() or new LinkedList<>(). They are mutable, therefore adding the elements using List#add or List#addAll is possible and a common way to do so.

List<String> mutableList = new ArrayList<>(Arrays.asList("one", null, "two"));

Here are listed ways to remove all the null elements from such List. Note it modifies the list.

  • List#removeIf(Predicate) as of

    mutableList.removeIf(Objects::isNull);
    
  • Iterator is a recommended way to remove elements from a List and is suitable (not only) for Java versions and lower

    Iterator<String> iterator = mutableList.iterator();
    while (iterator.hasNext()) {
        if (iterator.next() == null) {
            iterator.remove();
        }
    }
    
  • All the ways mentioned in the Immutable List section which always results in a new List.

Upvotes: 1

fabian
fabian

Reputation: 82531

In java 8 you can use Collection.removeIf:

list.removeIf(Objects::isNull);

Upvotes: 11

Flavio
Flavio

Reputation: 1

Using google.common.:

import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;

public List<String> removeBlanks(List<String> list) {
    return Lists.newArrayList(Iterables.filter(list, new Predicate<String>() {

        @Override
        public boolean apply(String arg) {
            return StringUtils.isNotEmpty(arg);
        }
    }));
}

Upvotes: 0

not efficient, but works

while(list.remove(null));

Upvotes: 2

Shafique Mahar
Shafique Mahar

Reputation: 1

for (int i = 0; i <array.size(); i++) {
    for (int j = 0; j < array.size()-i-1; j++) {
        if (array.get(j) > array.get(j+i)){
            Integer t = array.get(j+i);
            array.set(j+i,array.get(j));
            array.set(j,t);
        }
    }
}

for(int i = array.size()-1; i >= 0; i--){

Its a ascending order , what will be descending order of this problem ?

Upvotes: 0

Jon Tinsman
Jon Tinsman

Reputation: 586

If you are building the list yourself and not sure if the value is null or not you can also use CollectionUtils.addIgnoreNull(list,elementToAdd); This will prevent null elements from being added. This only works when constructing the list. If you are receiving the list from somewhere else and want to remove all non-null elements prior to using the list, then the list.removeAll(Collections.singleton(null)); will be best

Upvotes: 0

dveth
dveth

Reputation: 629

This should work:

list.removeAll(Collections.singleton(null));  

Upvotes: 54

Jigar Joshi
Jigar Joshi

Reputation: 240996

Extend ArrayList and override add() & addAll() method and simply don't allow null

or you could use list.removeAll(null); as shown here Which internally iterates the loop

Upvotes: 5

AlexR
AlexR

Reputation: 115398

Take a look on LambdaJ that allows you to manipulate collections "without" loops. Actually the loops are implemented inside the library but it really cool and it simplifies you code and makes it shorter.

Upvotes: 3

Related Questions