2
\$\begingroup\$

What this does?:

Interactions is an Enum whereas Interactable is an interface (not @Functional Interface). Every Interactable has a list of Interactions that it can do. The below code snippet, filters out all the objects that contains any of the provided Interactions. It does not check for all Interactions, so if any of the given Interactions found, it adds the object in interactableList. Once done iterative over the List, sends it back to the caller for further processing.

public List<Interactable> getObjectsByInteractions (final Interactions[] interactions) {
    final List<Interactable> interactableList = new ArrayList<>();
    for (Interactable object : objects) {
        List<Interactions> objectInteractions = object.getInteractions();
        for (Interactions interactions1 : interactions) {
            if (objectInteractions.contains(interactions1)) {
                interactableList.add(object);
                break;
            }
        }
    }
    return interactableList;
}

Concern:

Right now, I am using pre Java 8 code style to achieve the results. Since, it's the time of Java 8, I would request the reviewers to suggest Java 8 style.

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

There is nothing particularly wrong with your current code, although I have a couple of comments:

  • The name interactions1 of the local variable is slightly confusing.
  • Instead of having a break, you could have a separate method that determines if a given Interactable contains as interactions one of the given interactions.

With the Stream API, you could have the following:

public List<Interactable> getObjectsByInteractions(final Interactions[] interactions) {
    return objects.stream()
                  .filter(object -> Arrays.stream(interactions).anyMatch(object.getInteractions()::contains))
                  .collect(Collectors.toList());
}

This creates a Stream<Interactable> of your objects. It then filters out all the unwanted object: for that a Stream<Interactions> of the given interactions is created and anyMatch tells whether object.getInteractions() contains one of those interactions. Finally, the elements are collected into a list.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Note: If objects is an Interactable[] instead of a Iterable<? extends Interactable>, you should use Arrays.stream(objects) instead of objects.stream() \$\endgroup\$
    – Ferrybig
    Commented Apr 16, 2016 at 14:20
  • \$\begingroup\$ objects is an List<Interactable> which is Iterable<? extends Interactable>. But thanks for the input though. \$\endgroup\$
    – SSC
    Commented Apr 16, 2016 at 14:45

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.