java – For循环到Stream

我正在学习Streams和ParallelStreams,现在我尝试应用它.我正在更改包含for循环到流的代码,但我无法更改代码的某些部分.首先,可以将此代码减少为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());

最佳答案 如果我正确理解了您的代码,则对于输入列表中的每个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);
    }
}

(没有经过测试,但你应该明白了)

点赞