对于使用Java 8特性简化以下代码块,有什么建议吗?
int[] ans = new int[2];
list.forEach(i -> {
if (i > 0) {
ans[0] += 1;
} else if (i < 0) {
ans[1] += 1;
}
});
附言:我不确定是否应该发布此here
发布于 2018-10-13 15:26:01
如果你不想数零,那么你的代码就是最简单的。如果你想把零算作正数,那么你可以把它缩短成这样。
int[] ans = new int[2];
for (int i : list) ans[i < 0 ? 1 : 0] += 1;
发布于 2018-10-13 14:28:58
ans[0] = (int)list.stream().filter(x -> x < 0).count();
ans[1] = (int)list.stream().filter(x -> x > 0).count();
但我几乎不认为这是一种简化,你的解决方案已经尽可能简单了。
如果您确实想要计算零,可以简化为:
list.forEach(x -> ++ans[x >>> 31])
发布于 2018-10-13 16:10:05
我建议
int[] ans = new int[2];
list.forEach(i -> ans[i >>> 31] += i==0 ? 0 : 1);
其中,i >>> 31
丢弃除符号位之外的所有位(即,与i<0 ? 1 : 0
相同),第二个条件句柄为零。
我不敢说,它真的比原来的更好。
https://stackoverflow.com/questions/52789827
复制相似问题