如何将复杂的Java Stream转换为循环?

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

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 &lt; limit; i++) {
    Task task = taskFactory.createTask(); // assuming return type is some &#39;Task&#39; 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 &lt; limit; i++) {
    Optional.ofNullable(taskFactory.createTask())
      .map(taskMonitorFactory::startTask)
      .ifPresent(tasks::add);
}

Or old school:

for (int i = 0; i &lt; limit; i++) {
    Task task = taskFactory.createTask();
    if (task == null) {
        continue;
    }
    tasks.add(taskMonitorFactory.startTask(task));
}

huangapple
  • 本文由 发表于 2020年9月11日 00:36:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63834071.html
匿名

发表评论

匿名网友

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

确定