能力有限,此处不详细的记录 fiter的特性,毕竟我现在自己对它底层代码仍然看的是似懂非懂
注释部分的代码是我参照其他大大的博客写出的测试类,我在项目代码中发现了下面的那种用法,简单的一句话说就是自己写匹配规则。
我参考的博文https://jackyrong.iteye.com/blog/2150912
package test; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Collections2; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import org.checkerframework.checker.nullness.qual.Nullable; import java.util.Collection; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class Collection2FilterDemo { /*public static void main(String[] args) { List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom"); Iterable<String> result = Collections2.filter(names, Predicates.containsPattern("a")); for(String name : names) { System.out.println(name); } System.out.println("-----------------------"); for(String name : result) { System.out.println(name); } }*/ public static void main(String[] args) { List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom"); Collection<String> result = Collections2.filter(names, new Predicate(){ @Override public boolean apply(@Nullable Object input) { String str = (String) input; return str.contains("n") || str.contains("o")? true : false; } }); for(String name : names) { System.out.println(name); } System.out.println("-----------------------"); for(String name : result) { System.out.println(name); } } }
执行结果如下:
返回的结果表明:
filter的意义就是一个过滤器,按照一定的规则帮你自动过滤掉集合中的某些元素(集合按照一定的规则删除元素),而不是像以前那样 自己手动写一个for循环进行规则匹配,然后删元素的时候还要考虑下标之类的东西,我也是第一次见到这种东西,看起来觉得很新奇,貌似要学的东西还有黑多黑多~