2

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.

2
  • In your question you say you want to map fields by type. In your code you are using one single list. Either you should use a Map<String, List<IndexedField>> (with the String key being the type), or I don't understand what you're trying to do. Can you make this clearer so we can help you ? Commented Sep 29, 2017 at 12:57
  • Sorry, when I said map I ment stream api map function. Commented Sep 29, 2017 at 12:58

3 Answers 3

4

If I understood correctly:

 types.stream()
     .map(indexedEntities::getClassByType)
     .flatmap(x -> indexedEntities.getSearchFieldsFor(x).stream())
     .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I looked for. Thank you.
0

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);

1 Comment

It is not recommended to use forEach to populate other collection. Is it no thread safe and is it better to use collect
0

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.