문제

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:

  1. Simplify the search of objects in a pool-like manner, based on properties of the object.
  2. Provide a single central place where I can remove the objects from.

.

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....
도움이 되었습니까?

해결책

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
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top