I have this code. Here the map is Map<Data, Boolean>
int mask = 0;
for (Map.Entry<Data, Boolean> entry : map.entrySet()) {
if (entry.getKey().getValue() > 0 && entry.getValue()) {
mask = mask | (1 << (entry.getKey().getValue() - 1));
}
}
I want to calculate mask using Java stream. Here I tried to but only get then filter list. Don't know how calculate the mask here.
Integer mask = map.entrySet().filter( entry -> entry.getKey().getValue() > 0 && entry.getValue()).?
Generating Streams With Java 8, Collection interface has two methods to generate a Stream. stream() − Returns a sequential stream considering collection as its source. parallelStream() − Returns a parallel Stream considering collection as its source.
A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The features of Java stream are – A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
Stream map() in Java with examples Stream map(Function mapper) returns a stream consisting of the results of applying the given function to the elements of this stream. Stream map(Function mapper) is an intermediate operation.
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))});
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