I see that you are going with this - when a projectile (maybe a better class name than Bullet ) passes through BallisticGelPuddy , it either gets stuck or not. If it gets stuck, it accumulates in BallisticGelPuddy .
Rewrite the code if we used null instead:
for(Gun gun: guns) { final Bullet bullet = gun.shoot(); if(bullet != null) { bullets.add(bullet); } }
Pretty simple, right? If it exists, we want to add it.
Add an extra style back to:
for(Gun gun: guns) { gun.shoot().ifPresent(bullets::add); }
Effectively, these two things do the same thing, although the Optional approach is the term.
In this case, there is no difference between the two approaches, since you will always check for existence. Optional designed to protect against errors when handling null and allows you to express a more flexible chain of calls , but consider the practicality of using Optional in this scenario. This does not seem absolutely necessary for this case.
source share