mirzak
mirzak

Reputation: 1047

Adding data into a list while streaming another list

Let's say we have some entities, every entity has a list of searchable fields and a type. Is there a better (read more efficient way) to map those field in a list for every different type of entity.

Currently what I am doing is :

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

This works, but is there some better way to achieve this ? Maybe something with stream api.

Upvotes: 2

Views: 198

Answers (3)

Beno
Beno

Reputation: 987

You also can write by using only method references:

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

Upvotes: 0

Eugene
Eugene

Reputation: 120858

If I understood correctly:

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

Upvotes: 4

Naman
Naman

Reputation: 31888

You could shorten that to

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

Upvotes: 0

Related Questions