Search code examples
javasortinggenericscomparatorcomparable

Implement a Sortable class, that has dynamically generated properties


I want a class that can be sorted by properties (Probably using Comparable and Comparator). But instead of a normal class attributes, this class has a 'key value pair list'.

class Normal
{
   String attrib1;
   String attrib2;
   int attrib3;
}

This class attributes

class Special
{
    Map<String,Object> attributes =new HashMap<String,Object>()
}

Basically the class attributes are generated dynamically based on a scenario. So on a given scenario, the object property hashmap would have,

attrib1 : "value1"
attrib2 : "value2"
attrib3 : 3

So I need to implement the class 'Special', where a list of objects of type class 'Special', can be sorted by a given attibute (etc: sorted by attrib3).


Solution

  • First of all:

    public class Special {
    
         Map<String, Comparable> hashMap = new HashMap<String, Comparable>();
    }
    

    The values must implements Comparable interface.

    Then you can use a comparator like this:

    public class SpecialComparator implements Comparator<Special> {
    
        private String key;
    
        public SpecialComparator(String key) {
            this.key = key;
        }
    
        @Override
        public int compare(Special o1, Special o2) {
            // manage cases where o1 or o2 do not contains key
            return o1.hashMap.get(key).compareTo(o2.hashMap.get(key));
        }
    
    }
    

    And finally sort your list:

    Collections.sort(list, new SpecialComparator("somekey"));