如何使用Java的流(Streams)API编写代码,仅打印列表中出现的1和0?

huangapple 未分类评论41阅读模式
英文:

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&lt;Integer&gt; a) {

    List&lt;Integer&gt; diff = new ArrayList&lt;&gt;();

    for(int i = 1; i &lt; a.size(); i++) {
        diff.add(Math.abs(a.get(i) - a.get(i-1)));
    }

    long ct = diff.stream().filter(i-&gt; i==1).filter(i-&gt; i==0).count();
}

答案1

得分: 0

你可以像这样做。

或者,如果你想要计数:

在这两种情况下,筛选器会屏蔽掉最低位,并检查它是否等于原始数字。

英文:

You could do it like this.

diff.stream().filter(i-&gt; (i &amp; 1) == i).forEach(System.out::println);

Or if you want to count them

long ct = diff.stream().filter(i-&gt; (i &amp; 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.

huangapple
  • 本文由 发表于 2020年7月24日 20:58:55
  • 转载请务必保留本文链接:https://java.coder-hub.com/63074063.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定