Thursday, August 5, 2021

Leverage add() method for collection set as criteria check

 

We use the collection "set" to hold unique values and for adding an element we use the method “.add()” and the return-type of “.add()” is Boolean(True or False).

This method returns true if the element being added into the set is not present, else false. 


By leveraging the return type of "add()" with this method alone, the need of using ".contains()" in most cases (not all though) can be eliminated.  In this post, let's understand a basic scenario of replacing "contains" with "add" in the below example.




In the above logic we are checking if an element is present in a set or not.  If not present, add it to the set and execute some logic.   We are using a method (".contains()")  to check if an element is present or not and another method (".add()") to add the element.  

The same can be implemented by replacing two lines of "contains" and "add" by using the below code : 



Now the condition becomes TRUE only if the element is not found in the collection and the ".add()" will do.

For more methods on set :


".....Bazinga....."

No comments:

Post a Comment