Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if all items in a list are set to the same boolean value

Tags:

java

arraylist

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.

like image 281
HBU Avatar asked Apr 08 '19 18:04

HBU


People also ask

How do you check if all values are the same in a list Python?

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.

How do you check if all values in a list are equal in Java?

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.


2 Answers

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.

like image 93
Samuel Philipp Avatar answered Oct 13 '22 00:10

Samuel Philipp


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.

like image 27
Carrot Avatar answered Oct 13 '22 00:10

Carrot