英文:
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<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));
Now you need to select just one of these, the last one, with the maximum first element:
return stream.max(comparingInt(current -> 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<Integer>
, the above would suffice.
However, don't try to use streams for this. Use the original code, it's clearer and more efficient.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论