Simplifying the if-else condition using Java Functional Style Programming

s4ik4t :

Any suggestion to simplify the following code block using Java 8 features?

int[] ans = new int[2];
list.forEach(i -> {
    if (i > 0) {
        ans[0] += 1;
    } else if (i < 0) {
        ans[1] += 1;
    }
});

P.S. Not sure if I should post this here

Leo Aso :

If you don't want to count zeros, you code is as simple as it can get. If you wanted to count zeros as positive, however then you could shorten it to this.

int[] ans = new int[2];
for (int i : list) ans[i < 0 ? 1 : 0] += 1;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=113795&siteId=1