问题
I want to search in a Set without iterating manually over the elments but there does not seem to be a method to do Collections.search(myset, target, new ComparatorThing()). Am I not seeing something?
Thanks.
Edit:
- I am searching for another field than the natural order of the elements.
- As a manual workaround I used the following static method. Should okay, since you can't make any assumtions about the other using a custom field in the comparator anyways.
public static T search(final Set set, final T searchEntry, final Comparator comparator) {
for (final T entry : set) {
if (comparator.compare(entry, searchEntry) == 0) {
return entry;
}
}
return null;
}
回答1:
Take a look at http://commons.apache.org/collections/ which provides for example: public static java.util.Set SetUtils.predicatedSet(set, predicate)
回答2:
Need some more details here - are you attempting to search by an individual field in the Object contained in the Set
? Or just find a certain element in the Set
?
The idea of a Set
itself, as the bare interface, has no idea of ordering - you would need to iterate over every element.
However if you restrict yourself to SortedSet
, in which there is an ordering in place, you could possibly take advantage of the ordering, but since Set
s do not allow for random access, you would still have to either iterate over every element or know more information about the collection beyond just that it's a Set
.
Can you elaborate more on your algorithm and what you are trying to accomplish?
It is likely that a Set
is not the ideal way to represent the data you want to "search" through.
回答3:
Try contains(Object o)
, from the Collection
interface. The Set interface extends Collection, so all sets are required to implement the Collection methods.
Bear in mind, if all you know of your object to search is that it is guaranteed to be a set, you have no guarantee there IS any way to search without iterating over each element, as this contains()
method may or may not do depending on what type of set implementation you're actually using.
References
- Collection#contains()
回答4:
TreeSet has some methods that might be useful, for example ceiling
to search for the next element greater or equals to the search key, floor
to get the next lower element. Also headSet, tailSet and subSet to search for parts of a set lower, greater or between given limits.
来源:https://stackoverflow.com/questions/3363626/how-to-search-in-a-set-using-a-comparator