Skip to content
Advertisement

How to use stream to filter objects from HashSet that have empty value for certain fields?

I am looking for a way to filter only the Worker objects with a specific first name and empty lastName from the given HashSet. For example I want the code to return the record with firstName == scott and lastName == "".

JavaScript

Advertisement

Answer

filter is a non-terminal operation and the stream would be processed only when a terminal operation is encountered. More details

So you may use collect to display the filtered elements. Also use equals to compare strings instead of ==. Refer

JavaScript

If you want to do “null safety before I call ” .stream() ” on the collection object” then you could use Stream.ofNullable (since java 9)

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement