I have the following java method which returns the ID of a single matched movie from a list of movies, the filter criteria is the movie's attributes, all attributes provided must match:
public Optional<String> getIdFromMatchedMovie(List<Movie> movies, Map<String, Object> attributes)
{
Optional<Movie> movieOption =
movies.stream()
.filter(movie -> {
for (Map.Entry<String, Object> attr : attributes.entrySet()) {
Object returnedAttrValue = movie.getAttributes()
.get(attr.getKey());
// Attribute provided not exists in movie's attributes
// or the attributes value don't match
if (returnedAttrValue == null
|| !returnedAttrValue.equals(attr.getValue())) {
return false;
}
}
return true;
})
.findFirst();
if (movieOption.isPresent()) {
return movieOption.get().getId());
}
return Optional.empty();
}
Is there a way to rewrite this by remove the inner for loop and still leveraging the Java 8 Stream?