我想创建3个独立的现有Collection的Multimap实时视图。这样我只有一个中央集合来删除对象。
这应该是:
Multimap<String,Products> searchProductsByCategory=null;
Multimap<String,Products> searchProductsByType=null;
Multimap<String,Products> searchProductsByPlaces=null;
Collection<Products> productsAvailable=getAvailableProducts();
//Create indexed Views of the products
searchProductsByCategory = Multimaps.index(productsAvailable, productsToCategoryFunction);
searchProductsByType = Multimaps.index(productsAvailable, productsToTypeFunction);
searchProductsByPlaces = Multimaps.index(productsAvailable, productsToPlacesFunction);
//Get Customers from database
Collection<Customer> customers=getCustomersFromDatabase();
List<Product> productsReserved=new LinkedList();
for(Customer customer:customers){
Collection<String> categoriesChosen=getCustomerCategories(customer);
for(String category:categoriesChosen){
Collection<Product> tempResult=searchProductsByCategory.get(category);
if (tempResult.isEmpty()){
productsAvailable.removeAll(tempResult);
productsReserved.addAll(tempResult);
}
}
}
//Here continuation of functionality based on Types and Places....
答案 0 :(得分:3)
Multimaps.index()
未返回视图,并且没有查看implementations。
你必须自己写一个get()
只会过滤原始收藏。但是,它并不是非常有效,如果你不需要除get()
以外的其他方法,你可能最好不要创建一个辅助函数。
public class LiveIndexMultimap<K, V> implements Multimap<K, V> {
private final Collection<V> values;
private final Function<? super V, K> keyFunction;
public LiveIndexMultimap(Collection<V> values,
Function<? super V, K> keyFunction) {
this.values = values;
this.keyFunction = keyFunction;
}
public Collection<V> get(K key) {
return FluentIterable.from(values)
.filter(Predicates.compose(Predicates.equalTo(key),
keyFunction)))
.toList(); // Copy needed if you want your example to work
}
// Other methods left as an exercice to the reader
}