Bosko Sinobad
Bosko Sinobad

Reputation: 119

Lambda filter not working as expected

I'm using this lambda expression in my code:

File slika = new File(tempPath + File.separator + imena.stream().filter(x -> !x.trim().equals("null")).findFirst().get());

It's supposed to get a name from a file that was posted to my servlet that doesn't equal null. I checked the contents of the ArrayList<String> imena, and found out that it contains the following (separated by commas): null, null, null, Photo0098.jpg. The last one is the one I posted to the server, and the one that is supposed to get picked up by the filter, but instead I get a null pointer exception. That identical piece of code works on another servlet that also handles file uploads. Can someone tell me why my code is not working here, even though it works elsewhere in the same condition?

Upvotes: 3

Views: 956

Answers (3)

Mureinik
Mureinik

Reputation: 312289

Looks like the value in the list is an actual null, not a string with the content of "null". Using a method reference to Objects.nonNull is an elegant way of filtering them out:

File slika = 
new File(tempPath + 
         File.separator + 
         imena.stream().filter(Objects::nonNull).findFirst().get());
         // Here --------------^

Upvotes: 6

Nikolas
Nikolas

Reputation: 44496

Trimming the existing String never returns null since it contains anything to trim, else it would throw NullPointerException first. Filter directly the null values out.

imena.stream().filter(x -> x != null).findFirst().get();

Upvotes: 1

Carlos Laspina
Carlos Laspina

Reputation: 2231

That's because your element x is null. When you trying to trim your string occurs your NullPointerException.

Try this

File slika = new File(tempPath + File.separator + imena.stream().filter(x -> x != null).findFirst().get());

Upvotes: 2

Related Questions