将带有两个计数器的while循环转换为Java 14中的lambda表达式。

huangapple go评论64阅读模式
英文:

convert loop while with two counters into lambdas java 14

问题

Stream.iterate(18, r -> r >= 6, r -> r - 6).count().map(Integer::intValue).collect(Collectors.toList());
英文:

Hi i've tried to convert this method into a lambda expression

List<Integer> euclid(int x, int y){
        int q = 0; int r = x;
        while (r >= y){
            q++; r -= y;
        }
        return Arrays.asList(q, r);
 }

with this

Stream.iterate(18,r -> r >= 6, r -> r -=6 ).count().map(Integer::intValue).collect(Collectors.toList());

答案1

得分: 1

你需要维护这两个变量的状态。例如:

Stream<List<Integer>> stream = Stream.iterate(
    Arrays.asList(0, x),
    current -> current.get(1) > y,
    current -> Arrays.asList(current.get(0) + 1, current.get(1) - y));

现在你只需要从中选择其中一个,即最后一个,并且这个最后一个的第一个元素最大:

return stream.max(comparingInt(current -> current.get(0))).get();

如果你将 q/r 对存储或返回到一个更有意义的类型中,可能会更容易阅读;但既然你想返回一个 List<Integer>,上述代码就足够了。


然而,不要尝试将流(streams)用于这个问题。使用原始代码会更清晰和更有效。

英文:

You need to maintain the state of the two variables. For example:

Stream&lt;List&lt;Integer&gt;&gt; stream = Stream.iterate(
    Arrays.asList(0, x),
    current -&gt; current.get(1) &gt; y,
    current -&gt; Arrays.asList(current.get(0) + 1, current.get(1) - y));

Now you need to select just one of these, the last one, with the maximum first element:

return stream.max(comparingInt(current -&gt; current.get(0))).get();

It would probably be easier to read if you stored/returned the q/r pair in a more meaningful type; but since you want to return a List&lt;Integer&gt;, the above would suffice.


However, don't try to use streams for this. Use the original code, it's clearer and more efficient.

huangapple
  • 本文由 发表于 2020年8月26日 21:38:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/63598932.html
匿名

发表评论

匿名网友

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

确定