英文:
How to write code for printing only 1 and 0 present in the list using streams API java?
问题
public static void pickingNumbers(List<Integer> a) {
List<Integer> diff = new ArrayList<>();
for(int i = 1; i < a.size(); i++) {
diff.add(Math.abs(a.get(i) - a.get(i-1)));
}
long ct = diff.stream().filter(i -> i==1).filter(i -> i==0).count();
}
英文:
public static void pickingNumbers(List<Integer> a) {
List<Integer> diff = new ArrayList<>();
for(int i = 1; i < a.size(); i++) {
diff.add(Math.abs(a.get(i) - a.get(i-1)));
}
long ct = diff.stream().filter(i-> i==1).filter(i-> i==0).count();
}
答案1
得分: 0
你可以像这样做。
或者,如果你想要计数:
在这两种情况下,筛选器会屏蔽掉最低位,并检查它是否等于原始数字。
英文:
You could do it like this.
diff.stream().filter(i-> (i & 1) == i).forEach(System.out::println);
Or if you want to count them
long ct = diff.stream().filter(i-> (i & 1) == i).count();
In both of these cases the filter masks off the lower bit and checks to see if it is equal to the original number.
专注分享java语言的经验与见解,让所有开发者获益!
评论