Search code examples
javasortinggenericstreemap

Sorting TreeMaps by value


I'm looking to sort a TreeMap of Customer objects by a specific Customer property. The TreeMap is defined as so:

private TreeMap<Long,Customer> customerMap = new TreeMap<>();

Long is the type of ID for the customers stored.

I wrote a function to create a new TreeMap and pass a Comparator to its constructor which gets map entries, their values, that compares the specific field.

public Customer[] getCustomersByName() {
    TreeMap<Long,Customer> sortByName = new TreeMap<> (

        new Comparator<Map.Entry<Long,Customer>>() {
            @Override public int compare(Map.Entry<Long,Customer> cus1, Map.Entry<Long,Customer> cus2) {
                return cus1.getValue().getLastName().compareTo(cus2.getValue().getLastName());
            }
        }
    );
    sortByName.putAll(customerMap);
    
    // sortByName to Customer[] and return.

}

This doesn't work and throws: Cannot infer type arguments for TreeMap<>Java(16778094) at Line 2.

Perhaps, the issue is that the Comparator takes <Map.Entry<K,V>> to compare a TreeMap<K,V> and that is the issue.

How would I fix this though to sort by values but keep the customerMap type as is?

I know that TreeMaps are only sorted by keys. Is there a better data structure for this job perhaps so that I could store a bunch of Customer objects and sort them by different Customer properties without the operation being too expensive (not polynomial preferably)?


Solution

  • Set up a second TreeMap, using the customers last name as the key:

    TreeMap<String,Customer> sortByName  = new TreeMap<>();
    TreeMap<Long,Customer> sortByID = new TreeMap<>();
    ----------------
    sortByName.put(customer.getLastName(), customer);
    sortByID.put(new Long(customer.getID()), customer);
    ----------------
    return sortByName.values().toArray( new Customer[sortByName.size()] );
    '''