Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate mask using java stream

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()).?
like image 531
Riwimo Herbs Avatar asked Jun 16 '20 13:06

Riwimo Herbs


People also ask

What does stream () return?

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.

What is Strem in Java?

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.

What does stream () map do?

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.


2 Answers

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

like image 136
Jakob Em Avatar answered Sep 29 '22 17:09

Jakob Em


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))});
like image 42
Vinay Hegde Avatar answered Sep 29 '22 17:09

Vinay Hegde