How to calculate mask using java stream
You can map your entry to the calculated value and then apply the or
within a reduce operator:
map.entrySet().stream()
.filter(entry -> entry.getValue() && entry.getKey().getValue() > 0)
.mapToInt(entry -> (1 << (entry.getKey().getValue() - 1)))
.reduce(0, (r, i) -> r | i)
Edit: Added 0 as identity element to the reduce operation to have a default value of 0 if the map is empty.
Edit2: As suggested in the comments I reversed the filter order to avoid unnecessary method calls
Edit3: As suggested in the comments mapToInt
is now used
You can try this , but as Aniket said above here mask
is mutating not a good idea to use Strem.
map.entrySet().filter( entry -> entry.getKey().getValue() > 0 && entry.getValue()).forEach(k->{mask=mask | (1 << (k.getKey().getValue() - 1))});
Here is yet another alternative.
int mask = map.entrySet().stream().filter(Entry::getValue)
.mapToInt(e -> e.getKey().getValue()).filter(a -> a > 0)
.reduce(0, (a, b) -> a | (1<<(b-1)));