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
  • 21,685
  • 24
  • 196
  • 332
user2173372
  • 443
  • 5
  • 15

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
  • 131,796
  • 23
  • 122
  • 195
YCF_L
  • 51,266
  • 13
  • 85
  • 129
4

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

list.removeIf(e -> e != null && e.startsWith("H"));
Yassin Hajaj
  • 20,892
  • 9
  • 46
  • 83
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.
  • 52,579
  • 8
  • 80
  • 117