首页 > 解决方案 > 转换为流

问题描述

我想将从外部循环中断的以下代码转换为 Java 8 Streams。

private CPBTuple getTuple(Collection<ConsignmentAlert>  alertsOnCpdDay)
{
    CPBTuple cpbTuple=null;

    OUTER:
    for (ConsignmentAlert consignmentAlert : alertsOnCpdDay) {
        List<AlertAction> alertActions = consignmentAlert.getAlertActions();
        for (AlertAction alertAction : alertActions) {
            cpbTuple = handleAlertAction(reportDTO, consignmentId, alertAction);
            if (cpbTuple.isPresent()) {
                break OUTER;
            }
        }
    }
    return cpbTuple;
}

标签: javajava-8java-stream

解决方案


这里的每个答案都使用flatMap,直到 java-10都不是懒惰的。在您的情况下,这意味着alertActions完全遍历,而在 for 循环示例中 - 不是。这是一个简化的示例:

static class User {
    private final List<String> nickNames;

    public User(List<String> nickNames) {
        this.nickNames = nickNames;
    }

    public List<String> getNickNames() {
        return nickNames;
    }
}

还有一些用法:

public static void main(String[] args) {
    Arrays.asList(new User(Arrays.asList("one", "uno")))
            .stream()
            .flatMap(x -> x.getNickNames().stream())
            .peek(System.out::println)
            .filter(x -> x.equalsIgnoreCase("one"))
            .findFirst()
            .get();
}

java-8这将打印两个 oneand uno,因为flatMap不是懒惰的。

另一方面,java-10这将打印- 如果您想将示例翻译为1 对 1 one,这就是您关心的内容。stream-based


推荐阅读