Campbell Ritchie wrote:Liutauras, please explain the advantages you might get from using & rather than %.
Paul Clapham wrote:Creating an empty list and adding to it via the stream is bad form, there's a more straightforward way to produce the desired list.
Paul Anilprem wrote:Curious to know why. The given code seems fine to me in that resect, if the method is meant to selectively build a list of items from an input stream.
In my opinion, the author wanted to demonstrate that a stream should not modify external to pipeline objects.
Yes: (Minor point which Liutauras mentioned) The & operator will give a slight performance enhancement.
Liutauras Vilda wrote:. . . If you have anything to add - please do so.
Campbell Ritchie wrote:(Major point) What happens if you are looking for odd numbers and you use i % 2 == 1?
Now, that is a noce book. Maybe a bit old, but well worth reading.
Liutauras Vilda wrote:. . . Java Puzzlers by Joshua Bloch . . .
That applies even more for something like a hash map, where buckets are often chosen by array indices. You can use the formula h & c − 1 where h is the hash code (maybe rehashed) and c is the capacity (=potential number of buckets =length of backing array). Remember that − has a higher precedence than &. This works especially well when c is an exact power of two. Using % would risk passing negative indices to the array and the program will crash with an index out of bounds exception.
Liutauras Vilda wrote:. . . using bitwise AND we can't fall into this trap . . .