英文:
How to convert a complex Java Stream to loop?
问题
我有一个 Stream 表达式,我想将其转换为 Java 中的简单循环(可以是 forEach 或者 while)。以下是该表达式:
for (int i = 0; i < limit; i++) {
Task task = taskFactory.createTask();
if (task != null) {
TaskMonitor monitor = taskMonitorFactory.startTask(task);
tasks.add(monitor);
}
}
我理解 filter 的概念是类似于 if/else,而 map 的概念是针对每个条目进行操作,但我不确定该如何处理 generate 和 limit 函数。我对流处理还很陌生。有什么建议吗?
英文:
I have a Stream expression that I want to convert to a simple loop in Java(either forEach or while). Below is the expression:
Stream.generate(taskFactory::createTask)
.limit(limit)
.filter(Objects::nonNull)
.map(taskMonitorFactory::startTask)
.forEach(tasks::add);
I understand the concept that filter means if/else and map means for every entry, but I am not sure what to do about these generate and limit functions. I am really new to streams. Any suggestions?
答案1
得分: 2
generate
用于创建流,而 limit
表示应该检索多少个元素 - 您可以使用一些 for
循环来替代
for (int i = 0; i < limit; i++) {
Task task = taskFactory.createTask(); // 假设返回类型是某个 'Task' 类
if (task != null) {
task = taskMonitorFactory.startTask(task);
tasks.add(task);
}
}
英文:
generate
is for stream creation and the limit
tells how much elements should be retrieved - you can use some for
loop instead
for(int i = 0; i < limit; i++) {
Task task = taskFactory.createTask(); // assuming return type is some 'Task' class
if(task != null) {
task = taskMonitorFactory.startTask(task);
tasks.add(task);
}
}
答案2
得分: 1
您的代码翻译如下:
for (int i = 0; i < limit; i++) {
Optional.ofNullable(taskFactory.createTask())
.map(taskMonitorFactory::startTask)
.ifPresent(tasks::add);
}
或者老式写法:
for (int i = 0; i < limit; i++) {
Task task = taskFactory.createTask();
if (task == null) {
continue;
}
tasks.add(taskMonitorFactory.startTask(task));
}
英文:
Your stream translates to:
for (int i = 0; i < limit; i++) {
Optional.ofNullable(taskFactory.createTask())
.map(taskMonitorFactory::startTask)
.ifPresent(tasks::add);
}
Or old school:
for (int i = 0; i < limit; i++) {
Task task = taskFactory.createTask();
if (task == null) {
continue;
}
tasks.add(taskMonitorFactory.startTask(task));
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论