1

I am getting an error while running following code:

public class TestClass {

public static void main(String[] args) {
    var list = new ArrayList<String>();
    list.add("Harry");
    list.add("Marry");
    list.add(null);
    list.add("Larry");

    list.removeIf(e -> e.startsWith("H"));
    list.forEach(System.out::println);

    }
}

Getting following error:

Exception in thread "main" java.lang.NullPointerException
at test/test.TestClass.lambda$0(TestClass.java:14)
at java.base/java.util.ArrayList.removeIf(Unknown Source)
at java.base/java.util.ArrayList.removeIf(Unknown Source)
at test/test.TestClass.main(TestClass.java:14)

Why I am getting the unknow source error, it works fine if I provide following lambda:

list.removeIf(e -> e == null);
Naman
  • 27,789
  • 26
  • 218
  • 353
user2173372
  • 483
  • 7
  • 17

3 Answers3

7

null.startsWith("H") returns NullPointerException instead you have to check if the value is null or not then use startsWith:

list.removeIf(e -> e != null && e.startsWith("H"));
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
4

One of your entries is null and e.startsWith("H") gives a NullPointerException

list.removeIf(e -> e != null && e.startsWith("H"));
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
2

it works when you perform:

list.removeIf(e -> e == null);

because you're explicitly saying "remove all null elements", so there is no chance of NullPointerException here.

whereas:

 list.removeIf(e -> e.startsWith("H"));

is saying "remove all elements that start with 'H' " but if e is null then you're doomed as it will yield a NullPointerException.

Instead, check if it's not null prior to checking whether it starts with "Hi" or not.

list.removeIf(e -> e != null && e.startsWith("H"));
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126