Here's a way that counts zeroes as well:
int[] ans = new int[3];
list.forEach(i -> ans[Integer.signum(i) + 1] += 1);
The ans
array now holds 3 values: index 0 for negative count, index 1 for zero count and index 2 for positive count.
i.e. for the following input: [1, 2, 3, 0, -4, -5]
, the output would be: [2, 1, 3]
.
A more functional way, excluding zeroes:
Map<Integer, Long> bySignum = list.stream()
.filter(i -> i != 0)
.collect(Collectors.groupingBy(Integer::signum, Collectors.counting()));
Which produces this output: {-1=2, 1=3}
.