1

I have a map like this:

Map<String, TC> mapToSort= new HashMap<String, TC>(); 

the value is a class:

class TC {

    private int a;

    public TC(int a) {
        this.a = a;

    }
//getters-setters
    public int getA() {
        return a;
    }
    public void setA(int a) {
        this.a = a;
    }       
}

I want to sort this map not by the keys(that would be easy using TreeMap) but by the field "a" variable in the TC class. So elements with highest "a" values should be on top of the mapToSort. Is there any built-in or otherwise elegant solution to achieve this?

Sanyifejű
  • 2,610
  • 10
  • 46
  • 73

3 Answers3

0

Implement Comparable by your class and then put them in a TreeSet

class TC implements Comparable<TC> {

    private int a;

    public TC(int a) {
        this.a = a;
    }
//getters-setters
    public int getA() {
        return a;
    }
    public void setA(int a) {
        this.a = a;
    }

    @Override
    public int compareTo(TC tc){
        return this.a-tc.getA();     
    } 
}
Codey McCodeface
  • 2,988
  • 6
  • 30
  • 55
0

Use a TreeMap with custom Comparator for keys. In key objects keep a link to value objects. Implement your comparator to compare by values, not by keys. In your case you have to wrap a string with something like:

class Key{
   public Key(String key, TC value)
   {
      this.key = key;
      this.value = value;
   }
   String key;
   TC value;
}
Mikhail
  • 4,175
  • 15
  • 31
0

Something like this will get you a sorted list of the values.

List sortValues(Map mapToSort)
{
  List values = new ArrayList(mapToSort.values());
  Comparator<TC> tcComparator = new Comparator<TC>
  {
    public int compare(TC tc1, TC tc2)
    {
      return tc1.getA() - tc2.getA();
    }
  };
  Collections.sort(values, tcComparator);
  return values;
}
MikeFHay
  • 8,562
  • 4
  • 31
  • 52