Issue
I have a list like this:
int[] counting = new int[]{1,0,-1,-2,-1,-2,-1,0,1,2,1,0,-1,0,1,2};
I want to filter if there is a negative value between 0 and 0 numbers.
For above list, result should return 2 because between 0 and 0 there is a negative number and it also valid for third range.
List<Integer> result = Arrays.stream(counting).filter(x -> ).collect(Collectors.toList());
How can i collect range values? After that how can I check there is a negative number or not?
In other words I want to count how many pairs of (0, 0) there are with a negative value between them. So since there’s a negative value in -1,-2,-1,-2,-1 and one in -1, the count of such pairs is 2.
Solution
Don’t use a stream pipeline for that. Streams are well suited for independent processing and filtering of elements. They are not suited for processing that depends on the presence or absence of other elements in the stream (here 0 earlier and later).
Use a loop. Before entering the loop, check that the first element in the list is 0 as required, and throw an exception if not (so your example list from the question won’t pass this test). Declare some variables that we need during looping:
int negativeCount = 0;
boolean hasSeenNegativeSinceLastZero = false;
In your loop, each time you see a negative number, set hasSeenNegativeSinceLastZero
to true. Each time you see a 0, if hasSeenNegativeSinceLastZero
is true, then add 1 to the count and set hasSeenNegativeSinceLastZero
to false.
Answered By - Ole V.V.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.