Issue
I have a map in which its values are a simple pojo. For example (in a very loosely code):
Class Data{
int a;
Boolean b;
}
Map<Integer, Data> myMap = new HashMap<>();
Now the map is being populated with values. And at then end I would like to assert that all the b values of the data object of all map entries are, for example, true.
So I tried something like that:
private void computeAllBooleans(){
allBooleansStatus = true;
myMap.values()
.forEach(data ->
allBooleansStatus = allBooleansStatus && data.getB();
}
- Is there a more concise way to achieve that?
- Is there a way to assert it with JUnit (or other relevant frameworks like hamcrest, assertj, etc.) assertions?
(I noticed this link but didn't understand how can I use the suggested answers there...)
Solution
You can use allMatch
terminal operation to check all element of map like this:
myMap.values().stream().allMatch(Data::getB);
or use filter and count it like this:
myMap.values().stream().filter(Data::getB).count() == myMap.size();
Answered By - Hadi J
Answer Checked By - Clifford M. (JavaFixing Volunteer)