我想根据谓词筛选java.util.Collection。
当前回答
我写了一个扩展的Iterable类,它支持在不复制集合内容的情况下应用函数式算法。
用法:
List<Integer> myList = new ArrayList<Integer>(){ 1, 2, 3, 4, 5 }
Iterable<Integer> filtered = Iterable.wrap(myList).select(new Predicate1<Integer>()
{
public Boolean call(Integer n) throws FunctionalException
{
return n % 2 == 0;
}
})
for( int n : filtered )
{
System.out.println(n);
}
上面的代码将实际执行
for( int n : myList )
{
if( n % 2 == 0 )
{
System.out.println(n);
}
}
其他回答
我写了一个扩展的Iterable类,它支持在不复制集合内容的情况下应用函数式算法。
用法:
List<Integer> myList = new ArrayList<Integer>(){ 1, 2, 3, 4, 5 }
Iterable<Integer> filtered = Iterable.wrap(myList).select(new Predicate1<Integer>()
{
public Boolean call(Integer n) throws FunctionalException
{
return n % 2 == 0;
}
})
for( int n : filtered )
{
System.out.println(n);
}
上面的代码将实际执行
for( int n : myList )
{
if( n % 2 == 0 )
{
System.out.println(n);
}
}
您确定要筛选Collection本身,而不是迭代器吗?
看到org.apache.commons.collections.iterators.FilterIterator
或者使用apache commons的第四版org.apache.commons.collections4.iterators.FilterIterator
java8之前的简单解决方案:
ArrayList<Item> filtered = new ArrayList<Item>();
for (Item item : items) if (condition(item)) filtered.add(item);
不幸的是,这个解决方案不是完全通用的,它输出的是一个列表,而不是给定集合的类型。此外,在我看来,引入库或编写函数来包装这段代码似乎有些过分,除非条件很复杂,但随后可以为该条件编写函数。
在Java 8中,您可以直接使用此过滤器方法,然后执行此操作。
List<String> lines = Arrays.asList("java", "pramod", "example");
List<String> result = lines.stream()
.filter(line -> !"pramod".equals(line))
.collect(Collectors.toList());
result.forEach(System.out::println);
考虑使用支持泛型的更新的Collections框架谷歌Collections。
更新:谷歌集合库现在已弃用。你应该使用最新发布的番石榴。它仍然具有对集合框架的所有相同扩展,包括基于谓词进行筛选的机制。
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 如何检查IEnumerable是否为空或空?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder