如何在集合中搜索(使用比较器) [英] How to search in a Set (using a Comparator)

查看:157
本文介绍了如何在集合中搜索(使用比较器)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个集合中搜索,而不是手动迭代的elments,但似乎没有一个方法做Collections.search(myset,target,新的ComparatorThing())。我没有看到什么?



感谢。



编辑 >


  • 我正在搜索与元素的自然顺序不同的另一个字段。

  • 以下静态方法。



  code> 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)


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;
}

解决方案

Take a look at http://commons.apache.org/collections/ which provides for example: public static java.util.Set SetUtils.predicatedSet(set, predicate)

这篇关于如何在集合中搜索(使用比较器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆