Question

I first started working with a single HashMap such as:

private static Map<Broker, Integer> brokerSalesCountList = new HashMap<Broker, Integer>();

and used

private static ValueComparator4Broker bvc =  new ValueComparator4Broker(brokerSalesCountList);
private static TreeMap<Broker,Integer> sortedbrokerSalesCountList  = new TreeMap<Broker,Integer>(bvc);

sortedbrokerSalesCountList.putAll(brokerSalesCountList);

Here's my Value Comparator code:

public class ValueComparator4Broker implements Comparator<Broker> {

    Map<Broker, Integer> base;
    public ValueComparator4Broker(Map<Broker, Integer> base) {
        this.base = base;
    }

    @Override
    public int compare(Broker a, Broker b) {
        if (base.get(a) >= base.get(b)) {
            return -1;
        } else {
            return 1;
        }
    }
}

PROBLEM: Now I have more than 2 new Hash Maps to be sorted the same way, and rather than duplicating the code for ValueComparator4Broker class, I want to make a single generic and parameterized ValueComparator class which can be used by all new *HashMap*s:

private static Map<Area, Integer> areaBrokerCountList = new HashMap<Area, Integer>();
private static Map<Area, Integer> areaSalesTotalList = new HashMap<Area, Integer>();

I tried something like the following, but the code is erroneous and does not even accept the key object of my HashMap to be substituted for Type. Any help to refine the approach and a code example would be greatly appreciated:

import java.lang.reflect.Type;
import java.util.Comparator;
import java.util.Map;

public class ValueComparator implements Comparator<Type> {  
    Map<Type, Integer> base;
    public ValueComparator(Map<Type, Integer> base) {
        this.base = base;
    }

    @Override
    public int compare(Type a, Type b) {
        if (base.get(a) >= base.get(b)) {
            return -1;
        } else {
            return 1;
        } // returning 0 would merge keys
    }

}
Was it helpful?

Solution

I'm not so good at cold typing Generic code but here's the idea:

Use the class this way:

Map<Broker, Integer> brokerSalesCountList = new HashMap<Broker, Integer>();

private static ValueComparator<Broker> bvc =  new ValueComparator<Broker>(brokerSalesCountList);

Define the class here:

public class ValueComparator<T> implements Comparator<T> {  
    Map<T, Integer> base;
    public ValueComparator(Map<T, Integer> base) {
        this.base = base;
    }

    @Override
    public int compare(T a, T b) {
        if (base.get(a) >= base.get(b)) {
            return -1;
        } else {
            return 1;
        } // returning 0 would merge keys
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top