3

I am dealing with autogenerated protobuf classes as the value in my TreeBidiMap. That means that they cannot implement Comparable. But building a Comparator for them would be trivial. Is there an implementation for TreeBidiMap that works with Comparators and doesn't require their Keys and Values to implement Comparable? And if not, is there a good reason for that?

My requirements are fairly simple:

A Map, that is sorted by it's value.

But I feel like I have to bend over backwards to achieve this. Currently looking into TreeMultimap to potentially achieve this.

David Schumann
  • 13,380
  • 9
  • 75
  • 96
  • 2
    The docs say ["nope."](https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/bidimap/TreeBidiMap.html) I don't know protobuf, any reason you can't just wrap its objects in a Comparable? – markspace Jul 30 '21 at 14:52
  • You may refer to [Sort a Map by values](https://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values) – samabcde Jul 30 '21 at 15:00
  • How would this wrapping look like in the case of a generated class? Have a new class extend it and use that everywhere instead of the generated one? I feel like that might lead to more problems down the road if the generated class is changed, or the generation framework gets updated. – David Schumann Jul 30 '21 at 15:01
  • 1
    @samabcde I am looking for a solution where the structure stays sorted all the time. Almost all of the solutions just describe a sorting operation on a map. – David Schumann Jul 30 '21 at 15:02
  • Just wondering: can you use a `TreeMap` with your sorted values as keys of it? Or even use a `TreeMap` along with a `Map` if you want this to be bidirectional. – gthanop Jul 30 '21 at 15:05
  • 2
    Maybe you can check out [`DualTreeBidiMap`](https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/bidimap/DualTreeBidiMap.html). According to the docs, it's a bidi map with 2 instances of `TreeMap` to sort by keys and values, and has a constructor which accepts 2 comparators (1 for values and 1 for keys). – gthanop Jul 30 '21 at 15:14
  • @gthanop Thats actually what I have switched to now. I think that should work, thanks! – David Schumann Jul 30 '21 at 15:28
  • 1
    No problem. I hope it will work (I say *I hope* because I have never actually used it, but as I read the documentation on it, it sounded promising). I am just letting you know I have not tested it. Since you are requesting a bidirectional sorted map, I just had it as an idea. You know what I should say now: *continue at your own risk*... Hehe. – gthanop Jul 30 '21 at 15:35

0 Answers0