Search code examples
javahashmappriority-queue

Map and Priority Queues


I want to create a Map with key as an product id(Integer) and then have the value be a priorityQueue as the value. This will store all users object that have bought the same product. This needs to be in desc order based off some logic.

I'm not too sure how to order the pq in desc within a map. Normally I could just do (a,b) -> Integer.compare(b,a) but I am unsure in this case.

Map<Integer, PriorityQueue<User>> productAssociation = new HashMap<Integer, PriorityQueue<User>>();

Solution

  • Given a

    public class User {
        private final int valueToSortOn;
    
        public User(int valueToSortOn) {
            this.valueToSortOn = valueToSortOn;
        }
    
        public int getValueToSortOn() {
            return valueToSortOn;
        }
    }
    

    and a

    Map<Integer, PriorityQueue<User>> productAssociation = new HashMap<Integer, PriorityQueue<User>>();
    

    then a way to create a new queue instance with a lambda comparator could look like this:

        int productId = 42;
        PriorityQueue<User> productQueue = productAssociation.getOrDefault(productId, new PriorityQueue<>((u1, u2) -> u2.getValueToSortOn() - u1.getValueToSortOn()));