Lidia :
I need to find an element's key that's in a list of sets of elements. What's a better (faster) way to do it? Here's my code:
// get tags from an ArrayList of resources
boolean tagFound = false;
HashSet<Tag> resourceTags = new HashSet<>();
for (Resource resource : list) {
Set<Tag> tmpTags = resource.getTags();
resourceTags.addAll(tmpTags);
}
// get tag keys from all tags
for (Tag resourceTag : resourceTags) {
if (resourceTag.getKey().equals(tag.getKey())) {
tagFound = true;
break;
}
}
Naman :
You could simply get rid of the addAll
overhead if all you're going to do is iterate again over it to find an occurrence.
for (Resource resource : list) {
for (Tag resourceTag : resource.getTags()) {
if (resourceTag.getKey().equals(tag.getKey())) {
tagFound = true;
break;
}
}
}
If this was to be written in a functional manner, it would look like:
boolean tagFound = list.stream()
.flatMap(r -> r.getTags().stream())
.anyMatch(t -> t.getKey().equals(tag.getKey()));
Note: On performance, in an R x T matrix you would have to pay O(R x T)
runtime to search for an element unless they are hashed. In the latter case, if for example Tag
was hashed you could have simply performed a contains
based on the key
to lookup in O(1)
instead.
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=356737&siteId=1