Reputation: 101
I would like to create 3 separate Multimap live views of an existing Collection. Such that I have only one central collection to remove the objects from.
This is supposed to:
.
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....
Upvotes: 0
Views: 120
Reputation: 11715
Multimaps.index()
does not return a view, and there are no view implementations.
You'd have to write one yourself where get()
would just filter the original Collection. It's not terribly efficient, though, and if you don't need other methods than get()
, you'd probably be better off creating a helper function.
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
}
Upvotes: 3