有什么方法(方法,lambda或优雅的结构)在列表中找到基于给定比较器的元素?List ::包含比较器
我写了这样的方法:
private static <T> boolean contains(List<T> list, T item, Comparator<? super T> comparator) {
return list.stream()
.anyMatch(listItem -> comparator.compare(listItem, item) == 0
);
}
但我正在寻找的东西,这将是更优雅来取代它。
我不想添加任何依赖关系,所以没有番石榴,“公地”,等我真的想找一个漂亮的方式做到这一点在Java中8
编辑:一些例子是什么我会考虑更优雅(这里是使用代码):
// sadly, this method doesn't exist
// nor is there a static one in Collections
// but maybe you can think of another way?
if (list.containsSame(item, comparator)) {
// ...
}
那么,你写的代码怎么不满足你?它看起来很好(虽然在签名中我会提供一个“比较器 super T>”代替) – fge 2014-12-03 10:51:35
我觉得可以通过智能使用平台或语言来改善它。 – ymajoros 2014-12-03 11:31:05
与您自己的比较器一起使用流是几乎所有人都称之为“框架的巧妙使用”。由于lambda,这也是最“漂亮”的方式。你还能想要什么? – specializt 2014-12-03 11:37:03