I have an ArrayList which is populated by a random number of GameObj
instances each time the program is run.
If an object makes contact with another object in the ArrayList, it will set a boolean called visible
from true
to false
.
Is there a way to check if all of the item instances in the ArrayList have been set to false
through:
XXXX.visible = false
Once I can check if they are all set to false
.
You can convert the list to a set. A set cannot have duplicates. So if all the elements in the original list are identical, the set will have just one element. if len(set(input_list)) == 1: # input_list has all identical elements.
distinct() Let's look at one particular solution making use of the distinct() method. If the count of this stream is smaller or equal to 1, then all the elements are equal and we return true. The total cost of the operation is O(n), which is the time taken to go through all the stream elements.
You can use Stream.noneMatch()
to do this:
if (bricks.stream().noneMatch(GameObj::isVisible)) {
doStuffIfAllBricksAreInvisible();
}
This returns true, if all bricks are invisible.
Additionally I would recommend to take a look at Stream.allMatch()
, which returns true, if all elements of the list match the given predicate.
Using allMatch()
this would look like this:
if (bricks.stream().allMatch(b -> !b.isVisible())) {
doStuffIfAllBricksAreInvisible();
}
To complete this, you also can take a look at Stream.anyMatch()
, which returns true, if one of the elements matches the given predicate.
If you are using Java <8, one way will be to store the arraylist size on intialisation in a variable( say variable name be count).
On change of flag from true to false, decrease the count by 1. If flag is already false, do nothing. Now you can just check the count is 0 or not.
If count is 0, print "Well done, Game over" or else continue the game.
For Java 8 or up, you can go for streams API as suggested in other answers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With