I am getting huge list and it has two fields as follows:

Number   Designation
10       Principal
10       Teacher
10       Dean
10       Peon

Map map = new HashMap<>();

I am using Map to avoid duplicates.

{Dean, principal, teacher, peon} are in descending priority and the values can be overwritten. At first, principal is put in map, then it shouldn't allow teacher to override because of higher priority with principal, later principal would be overwritten by dean but peon cannot overwrite dean.

How can I achieve this? Which algorithm applies here? any ideas?

Output will be:

10 Dean
  • 1
    It's not clear what your criteria are, but maybe you need to write your own custom Comparator to contain whatever special comparison rules you have. Mar 6, 2017 at 21:56
  • The priority requirement is fixed as this -> {Dean, principal, teacher, peon}. When ever Number 10 arrives it should check the Designation priority and put in Map. Mar 6, 2017 at 21:58
  • 1
    Your edit seems to make the problem less clear.
    – JimmyJames
    Mar 6, 2017 at 22:05

2 Answers 2


Assign a integer rank to each value. If rank of an existing value in the map for your key is less than the candidate value, replace it. If it isn't: don't.


Write a method which accepts input (Number, Designation) and then evaluate the priority of the designation if there is already a key with the "Number" in the HashMap. If the existing value has higher priority do not add the new value else add the new value for the key . Below is the sample code which may help you

private Map map = new HashMap<Number,String> (); 
//Enum values defining the Designations available
private Enum Desginations{DEAN, PRINCIPAL, TEACHER, PEON}
// Input method which accept the number and designation
public void addValueToMap(int number, String desgination){
        if (compareDesignation(desgination, map.get(number)) >0 )
             map.put(number, designation);
// if you want to add other keys
        map.put(number, designation);
 //Method to compare the priority of designation for the existing and new value for the same key
 private int compareDesignation(String inputDesignation, String existingDesgination){
//negative of result because the order of Designations in Enum is defined where the lowest value has the max priority 
  return -(Desginations.inputDesignation.getValue() - Desginations.existingDesgination.getValue())


//Method to print the existing map key and values
public void printDesignationsMap(HashMap designationsMap){
for (Map.Entry<KeyType, ValueType> entry : designationsMap.entrySet())
   System.out.println(entry.getKey()+" : "+entry.getValue());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.