Search code examples
javacollectionshashmapcomparatortreemap

Copy values from a HashMap to TreeMap


I want to copy a value from HashMap to a TreeMap to get the sorted map according to the Keys of Objects.

Here is my code:

    private static Map<Product,String> sortingUsingTreeMap(Map<Product,String> descriptionByProducts){
    final Map<Product,String> sortedMap = new TreeMap<Product,String>();
    for(Map.Entry<Product, String> element:descriptionByProducts.entrySet()) {
        sortedMap.put(element.getKey(), element.getValue());
    }

    sortedMap.putAll(descriptionByProducts);
    return sortedMap;
}

I am getting this error:

Exception in thread "main" java.lang.ClassCastException: compare.Product cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(TreeMap.java:1294)
at java.util.TreeMap.put(TreeMap.java:538)

This is my "Product" model class. The keys in the map is a Product Object.

public class Product {

private String prodId;
private String prodName;

public String getProdId() {
    return prodId;
}

@Override
public String toString() {
    return "Product [prodId=" + prodId + ", prodName=" + prodName + "]";
}

public Product(String prodId, String prodName) {
    super();
    this.prodId = prodId;
    this.prodName = prodName;
}

public void setProdId(String prodId) {
    this.prodId = prodId;
}

public String getProdName() {
    return prodName;
}

public void setProdName(String prodName) {
    this.prodName = prodName;
}
}

Looked at various answers and made one custom comparator:

import java.util.Comparator;

public class ProductComparator implements Comparator<Product>{

public ProductComparator() {
}

@Override
public int compare(Product o1, Product o2) {
    return o1.getProdId().compareTo(o2.getProdId());
}

}

How do I resolve this error? Thanks in Advance.


Solution

  • Thanks @AlexITC for the solution to this issue. I updated the method:

        private static Map<Product,String> sortingUsingTreeMap(Map<Product,String> descriptionByProducts){
    final Map<Product,String> sortedMap = new TreeMap<Product,String>(new ProductComparator());
    for(Map.Entry<Product, String> element:descriptionByProducts.entrySet()) {
        sortedMap.put(element.getKey(), element.getValue());
    }
    
    sortedMap.putAll(descriptionByProducts);
    return sortedMap;
    

    }