static class FilteredCollection<E> extends AbstractCollection<E> { //存储待处理的集合 final Collection<E> unfiltered; //存储过滤规则 final Predicate<? super E> predicate; FilteredCollection(Collection<E> unfiltered, Predicate<? super E> predicate) { this .unfiltered = unfiltered; this .predicate = predicate; } //根据新的过滤规则和原来的过滤规则合并创建一个新的容器 Collections2.FilteredCollection<E> createCombined(Predicate<? super E> newPredicate) { return new Collections2.FilteredCollection( this .unfiltered, Predicates.and( this .predicate, newPredicate)); } //添加元素方法 public boolean add(E element) { //根据过滤规则进行测试是否符合,如果符合便进行添加 Preconditions.checkArgument( this .predicate.apply(element)); return this .unfiltered.add(element); } //添加一个容器中所有元素 public boolean addAll(Collection<? extends E> collection) { Iterator i$ = collection.iterator(); //遍历容器,并对每一个容器进行塞选操作 while (i$.hasNext()) { Object element = i$.next(); Preconditions.checkArgument( this .predicate.apply(element)); } //如果都满足就添加 return this .unfiltered.addAll(collection); } public Iterator<E> iterator() { return Iterators.filter( this .unfiltered.iterator(), this .predicate); } public int size() { return Iterators.size( this .iterator()); } } |