I have some exercises which in one tells me that giving a list which contains nulls, I must first sort it alphabetically and remove the nulls, I tried this since streams are required.
Stream<String> lista = Stream.of("p","a","b", null,"c", null,"b", null,"d","j", null,"z","x");
System.out.print("Lista en orden y sin nulos: El primero es ");
lista.sorted()
.filter(x -> x != null)
.forEach(x -> System.out.print(x));
As I have seen with that .filter
I should remove the nulls but when compiling it skips me:
Exception in thread "main" java.lang.NullPointerException.
The only problem with your code is the order in which you try to call the Stream methods, since it
sorted()
basically compares the elements using the interfacecomparable
, specifically the methodcompareTo()
that includes said interface (if I'm not mistaken!)Whereupon, when you try to do
.compareTo(otroObjeto)
in anull
, it crashes. The easiest solution is... change the order in which you callsorted()
andfilter()
!In the comments there is a TLDR; For those who do not want to read so much.