Sobes.tech
Senior

What collection do you use for the top 10 most expensive products in real-time with support for a sorted list?

sobes.tech AI

Answer from AI

To support the top 10 most expensive items in real-time with a sorted list in Java, you can use a data structure that efficiently supports insertion, deletion, and sorting by price.

The optimal choice would be a PriorityQueue with a size limit of 10, where upon adding a new item, it checks whether the item's price exceeds the minimum price in the queue. If it does, the minimum element is removed, and the new item is added. This maintains the top 10 by price.

Example:

PriorityQueue<Product> topProducts = new PriorityQueue<>(10, Comparator.comparingDouble(Product::getPrice));

void addProduct(Product p) {
    if (topProducts.size() < 10) {
        topProducts.offer(p);
    } else if (p.getPrice() > topProducts.peek().getPrice()) {
        topProducts.poll();
        topProducts.offer(p);
    }
}

// To get the list in sorted order (from most expensive to least):
List<Product> sortedTop = new ArrayList<>(topProducts);
sortedTop.sort(Comparator.comparingDouble(Product::getPrice).reversed());

If faster sorting and frequent updates are needed, consider using a TreeSet with a custom comparator, but keep in mind that TreeSet does not allow duplicates by key, so you need to ensure element uniqueness.