28
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?

Kai
  • 38,985
  • 14
  • 88
  • 103
Noufal Panolan
  • 1,357
  • 2
  • 14
  • 27
  • 5
    Without you writing any iterations, or at all? http://stackoverflow.com/questions/4819635/how-to-remove-all-null-elements-from-a-arraylist – LuckyLuke Dec 19 '11 at 09:25

10 Answers10

54

This should work:

list.removeAll(Collections.singleton(null));  
jmj
  • 237,923
  • 42
  • 401
  • 438
dveth
  • 619
  • 5
  • 9
11

In java 8 you can use Collection.removeIf:

list.removeIf(Objects::isNull);
fabian
  • 80,457
  • 12
  • 86
  • 114
5

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

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
  • 5
    I don't like extending such classes, as it could lead to confusing code. You should also keep in mind that you can also add items to the list with a [ListIterator](http://docs.oracle.com/javase/1.4.2/docs/api/java/util/ListIterator.html#add%28java.lang.Object%29) – Kai Dec 19 '11 at 09:36
3

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.

AlexR
  • 114,158
  • 16
  • 130
  • 208
2

not efficient, but works

while(list.remove(null));

1

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.

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
0

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

Jon Tinsman
  • 566
  • 4
  • 21
0
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 ?

beresfordt
  • 5,088
  • 10
  • 35
  • 43
  • Questions should be asked on a separate thread. [Click here](http://stackoverflow.com/questions/ask) if you want to ask your question. Answering a question means answering a question, not asking yet another question. – Damodar Dahal Apr 10 '16 at 16:21
0

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);
        }
    }));
}
Flavio
  • 1
  • 1
0

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

list.stream()
    .filter(Objects::nonNull)
    .collect(Collectors.toList())
reubennn
  • 186
  • 1
  • 7