在流式传输另一个列表时将数据添加到列表中

Adding data into a list while streaming another list

假设我们有一些实体,每个实体都有一个可搜索字段列表和一个类型。是否有更好的(阅读更有效的方法)将这些字段映射到每个不同类型的实体的列表中。

目前我正在做的是:

final Collection<IndexedField> indexedFields = new ArrayList<>();
for (String type : types) {
    final Class<? extends IndexedEntity> targetClass = indexedEntities.getClassByType(type);
    indexedFields.addAll(indexedEntities.getSearchFieldsFor(targetClass));
}

这行得通,但是有更好的方法来实现吗?也许有流 api.

您可以将其缩短为

types.stream().<Class<? extends IndexedEntity>>map(
            type -> indexedEntities.getClassByType(type)).<Collection<? extends IndexedField>>map(
            targetClass -> indexedEntities.getSearchFieldsFor(targetClass)).forEach(indexedFields::addAll);

如果我理解正确的话:

 types.stream()
     .map(indexedEntities::getClassByType)
     .flatmap(x -> indexedEntities.getSearchFieldsFor(x).stream())
     .collect(Collectors.toList());

您也可以仅使用方法引用来编写:

final Collection<IndexedField> indexedFields = types.stream()
                                       .map(indexedEntities::getClassByType)
                                       .map(indexedEntities::getSearchFieldsFor)
                                       .flatMap(Collection::stream)
                                       .collect(Collectors.toList());