Anam Qureshi
Anam Qureshi

Reputation: 311

Check if all values of a map are true

I have one Map<String, Boolean> map = new HashMap<>();.
Consider there are five keys in it.

map.put("A", true);
map.put("B", true);
map.put("C", false);
map.put("D", true);
map.put("E", true);

I need to set one boolean flag as true if all the values in the above map are true.
If any value is false then i need to set boolean flag as false

I can iterate this map and do it like old ways but i want to know how can i do this in a single line by streaming on this map.

Upvotes: 5

Views: 11402

Answers (5)

Praveen
Praveen

Reputation: 9335

you can use allMatch

boolean flag = map.values().stream().allMatch(x -> x);

There is a catch for allMatch. If the collection is empty, then allMatch will return true

So if you want to set flag to true if map is not empty and all values are true then;

boolean flag = !map.isEmpty() && map.values().stream().allMatch(x -> x);

or as @Holger suggested

boolean flag = !map.containsValue(false)

Upvotes: 13

Dietmar H&#246;hmann
Dietmar H&#246;hmann

Reputation: 397

I have another solution. It assumes map is not empty and does not contain any nulls. If that assumption is correct we can just use this:

boolean flag = ! map.values().contains(false);

Ok - it does not use streams ...

Upvotes: 6

daniu
daniu

Reputation: 14999

Just to give another solution :

boolean result = map.values().stream().reduce(true, Boolean::logicalAnd);

Upvotes: 0

Johannes H.
Johannes H.

Reputation: 6167

boolean result = !map.values().stream().anyMatch(Boolean.FALSE::equals); will do.

Upvotes: 3

Flown
Flown

Reputation: 11740

There is nothing wrong with the "old way". But if you insist, you could go over all your Map#values and use Stream#allMatch.

boolean allTrue = map.values().stream().allMatch(v -> v);

Upvotes: 3

Related Questions