Ahmed Ibrahim
Ahmed Ibrahim

Reputation: 144

Stream filter method with underscore

i was answering problems on codefights and i found this problem

inputArray without elements k - 1, 2k - 1, 3k - 1 etc.

Example

For inputArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and k = 3,

the output should be extractEachKth(inputArray, k) = [1, 2, 4, 5, 7, 8, 10].

one of the answers was the following code which i couldn't understand.

int i;

int[] extractEachKth(int[] inputArray, int k)

{

   return Arrays.stream(inputArray).filter(__ -> ++i % k > 0).toArray();

}

Upvotes: 2

Views: 592

Answers (1)

Xvolks
Xvolks

Reputation: 2155

The filter method of the stream excludes elements that the expression after the arrow evaluates to false.

In other words it keeps the values when the expression evaluates to true.

As pointed by @Snehal Patel in the comment, the __ is variable containing the current value submitted to the filter. It is a common practice to use _ or __ as a name of an unused parameter (specially in Swift language for example).

Upvotes: 2

Related Questions