I'm working on a java spring application and want to filter and get specific item in mongodb database, but it is quite messy my code and would like to know how to improve my code when working with stream filter
public String getPrimaryTechnology(String id){
Article article = articleRepository.findById(id).get();
List<AWS_entity> aws_entitiesList = article.getAws().getEntities();
Predicate<AWS_entity> priority1 = aws -> article.getTitle().contains(aws.getName())
&& aws.getCategory().equals("TITLE");
Predicate<AWS_entity> priority2 = aws -> article.getTitle().contains(aws.getName())
&& aws.getCategory().equals("COMMERCIAL_ITEM"));
Predicate<AWS_entity> priority3 = aws -> article.getTitle().contains(aws.getName())
&& (aws.getCategory().equals("ORGANIZATION") || aws.getCategory().equals("OTHER"));
Optional<AWS_entity> aws_entity = Optional.ofNullable(aws_entitiesList
.stream()
.sorted(Comparator.comparing(AWS_entity::getCount).reversed())
.filter(priority1)
.findFirst()
.orElse(aws_entitiesList.stream()
.filter(priority2)
.findFirst()
.orElse(aws_entitiesList.stream()
.filter(priority3)
.findFirst().orElse(null)
)
))
;
if(!aws_entity.isPresent())
return "none identified";
else return aws_entity.get().getName();
}
.orElse
its argument will always be evaluated, regardless of whether or not it is actually required. Considering you are going through (potentially) large collections, this can be quite expensive (read: slow). Use.orElseGet
in such a case: the expensive operation will then only be performed when required..orElse
should be reserved for cases when you return a constant (i.e.Collection.emptyList
,""
,0
).