For循环到Stream

时间:2015-07-07 13:55:20

标签: java loops java-8 java-stream

我正在学习Streams和ParallelStreams,现在我尝试应用它。我正在将包含 for 循环的代码更改为 streams ,但我无法更改代码的某些部分。首先,可以将此代码减少为Streams吗?

使用foreach循环

private List<BasicDBObject> linhaCriativa(List<BasicDBObject> linhas) {
        List<BasicDBObject> lista = new ArrayList<>();
        for (BasicDBObject db : linhas) {
            if (!db.toMap().containsKey("spec_linha-criativa")) {
                lista.add(db);
                continue;
            }
            String[] linhaCriativa = db.get("spec_linha-criativa").toString().split(";");
            if (linhaCriativa.length > 0) {
                for (String criativa : linhaCriativa) {
                    BasicDBObject dbObject = (BasicDBObject) db.copy();
                    dbObject.replace("spec_linha-criativa", criativa);
                    lista.add(dbObject);
                }
            } else {
                lista.add(db);
            }
        }
        return lista;
    }

我可以这样做,但是当db.toMap()。 containsKey (“spec_linha-criativa”)

时我无法做到
List<BasicDBObject> notContains = linhas.parallelStream().filter(m -> !m.toMap().containsKey("spec_linha-criativa")).collect(Collectors.toList());

1 个答案:

答案 0 :(得分:2)

如果我正确理解您的代码,对于输入列表中的每个BasicDBObject,您将提取一个或多个BasicDBObject,并将它们添加到输出列表。

这是flatMap()操作:

return linhas.stream()
             .flatMap(this::extractOutputDbObjectsFrom)
             .collect(Collectors.toList());

现在您需要创建extractOutputDbObjectsFrom方法:

private Stream<BasicDBObject> extractOutputDbObjectsFrom(DbObject db) {
    if (!db.toMap().containsKey("spec_linha-criativa")) {
        return Stream.of(db);
    }

    String[] linhaCriativa = db.get("spec_linha-criativa").toString().split(";");
    if (linhaCriativa.length > 0) {
        return Arrays.stream(linhaCriativa).map(criativa -> {
            BasicDBObject dbObject = (BasicDBObject) db.copy();
            dbObject.replace("spec_linha-criativa", criativa);
            return dbObject;
        });
    } else {
        return Stream.of(db);
    }
}

(未经过测试,但您应该明白这一点)