我想在集合中进行搜索,而不需要手动迭代元素,但似乎没有方法可以执行 Collections.search(myset, target, new ComparatorThing())。难道我没看到什么吗?
谢谢。
编辑:
- 我正在寻找元素自然顺序之外的另一个领域。
- 作为手动解决方法,我使用了以下静态方法。应该没问题,因为无论如何您都无法在比较器中使用自定义字段对对方做出任何假设。
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;
}
最佳答案
看看http://commons.apache.org/collections/其中提供了示例:public static java.util.Set SetUtils.predicatedSet(set, predicate)
关于java - 如何在集合中搜索(使用比较器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3363626/