0

I have the following treemap

private TreeMap<Long, HashMap<Long, Entry>> index;

Entry contains:

int tf //count
ArrayList<long> off //positions

For each entry in the treemap, I would like to sort the hashmaps by tf. In the following picture, tf of [3] has a bigger value of tf of [0] so I would like to move it to be at the beggining. How can I do that?

enter image description here

nabrugir
  • 1,839
  • 2
  • 22
  • 38

3 Answers3

0

I believe the fundamental problem with your question is that HashMaps are not sortable by definition. Secondly, a variable definition that is more generic may prove useful:

private SortedMap<Long, SortedMap<Entry, Long>> index;

Noticed I switched the order of Entry and Long. This is because Maps only sort based on the key. You'd have to either make Entry implement Comparable or provide a custom Comparator when you instantiate that Map.

micker
  • 878
  • 6
  • 13
0

You cannot order a HashMap. Trying to do so breaks the way a HashMap stores and finds the elements added to it

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
0

What you are trying to do here (as I understand it) is sorting the treemap by its value, while TreeMap can only sort by its keys. more details here - TreeMap sort by value

You may try writing your own sorting method and store the result of sort in a linkedHashMap instead of Treemap. That way you can be able to access the entries in the exact order you added that to the linkedHashMap. Note: with each change happening to the original map, you ll need to sort it and move it to a different linkedHashMap. Which is very clumsy.

You may consider using different object model for your program.

Community
  • 1
  • 1
Dipanjan
  • 1
  • 1
  • 3