In memory index of product ID's, ordered by inventory_count
I have a index that I need to re-order whenever some new data comes into the web application.
I have, in memory, a list of products and the inventoryCount for each product.
I want to keep an index of productID's, sorted by inventory count.
So if new orders come in, the inventory gets modified and so I have to update the product_inventory index.
What's the fastest way to do this?
I can't use the database for this, it has to be all in-memory via开发者_运维技巧 java code
You can use a comparator to maintain maintaining a list of productIDs in order of inventory count. The comparator looks up the inventory count given the product ID and uses this as the basis for comparison.
Assuming you have the class:
class Product {
int productID;
int inventoryCount;
}
The comparator would look like:
class ProductInventoryComparator implements Comparator<Product> {
public int compare(Product p1, Product p2) {
return p1.inventoryCount-p2.inventoryCount;
}
}
With this, you can then maintain a sorted List by inserting the element in the correct location to keep the list sorted. To find the insertion place in the list, use Collections.binarySearch to locate the insertion point:
ProductInventoryComparator comp = new ProductInventoryComparator();
List<Product> productList = new ArrayList<Product>();
Product p = ...new product to add;
int pos = Collections.binarySearch(productList, comp, p);
if (pos<0) { // not found
productList.add(-pos-1);
}
You mention that you want a list of ProductIDs, presumably a list of integers - if possible I recommend creating a simple object for these like Product above, to avoid the overhead of boxing/unboxing integer values.
精彩评论