【问题标题】:Static action and Break from Java 8 stream forEach on HashMap?HashMap 上的 Java 8 流 forEach 的静态操作和中断?
【发布时间】:2019-09-27 08:31:46
【问题描述】:

当在 Iterable 上使用外部迭代时,我们使用静态操作和从增强的 for-each 循环中中断:

for (Entry<String, String> w : Context.getWindows().entrySet()) {
    if (w.getValue().equals(Context.getDriver().getWindowHandle())) {
        Context.removeWindow(w.getKey());
        break;
    }
}
Context.getDriver().close();

我们如何使用 Java 8 lambda 表达式中的内部迭代来中断或返回,例如:

Context.getWindows().forEach(obj -> {
   //what to do here?
})

我在https://stackoverflow.comstream() filterfindFirst 上找到了其他问题,但这个解决方案返回一个对象。就我而言,我想执行一个静态动作并中断;

Optional<SomeObject> result =
    Context.getWindows().stream().filter(obj -> some_condition_met).findFirst();

【问题讨论】:

    标签: java arrays lambda foreach java-8


    【解决方案1】:

    这应该翻译成类似

    Context.getWindows().entrySet().stream()
        .filter(e -> e.getValue().equals(Context.getDriver().getWindowHandle()))
        .map(e -> e.getKey())
        .findFirst()
        .ifPresent(k -> Context.removeWindow(k));
    Context.getDriver().close();
    

    或者,更简洁

    Context.getWindows().entrySet().stream()
        .filter(e -> e.getValue().equals(Context.getDriver().getWindowHandle()))
        .map(Map.Entry::getKey)
        .findFirst()
        .ifPresent(Context::removeWindow);
    Context.getDriver().close();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-12
      • 1970-01-01
      • 1970-01-01
      • 2016-08-27
      • 1970-01-01
      • 1970-01-01
      • 2020-01-27
      相关资源
      最近更新 更多