0

I have a TreeMap with the key being a string and the value a pair, type (Integer, String) and I need my treeMap to be ordered by the key of the Pair. I haven't worked with Pairs much and am curious the best way to do this.

I am having a hard time creating a TreeMap comparator for the pair. I am currently adding the pair to the Map upon my add function. Do I need to create a subclass for the Pair itself and use a comparator within the subclass or can I just access the Pair within a treeMap class via comparator. This is what I am trying to add a comparator to.

private final TreeMap<String, Pair<Integer, String>> cacheFiles;
public Cache(int size) {
    this.cacheFiles = new TreeMap<String, Pair<Integer, String>>();
    this.size = size;
    this.currSize =0;
}
public void add(String fname, int cost, String contents) {
    if (!cacheFiles.containsKey(fname)) {
        updateSize(cost);
        cacheFiles.put(fname, new Pair<Integer, String>(cost, contents));
    }

I need my TreeMap ordered by "cost" so that when I remove the firstEntry or lastEntry it is removing the largest cost or the smallest as I cannot keep track of a key for every Map entry that may have to be removed at a given point.

This is sorta what I've been trying...Yet the editor does not like it whenever I try to use comparator of Pair.

Thanks for any help!

    public Cache(int size) {
    this.cacheFiles = new TreeMap<String, Pair<Integer, String>>(new Comparator<Pair>() {
        public int compare(Pair<Integer, String> p1, Pair<Integer, String> p2) {
            return o1.getKey().compareTo(o2.getKey());
        }
        });
    this.size = size;
    this.currSize =0;
}
tw123
  • 1
  • 1
  • I guess you get the value(Pair) from the map in the comparator & sort the keys based on it – nitnamby Apr 27 '18 at 21:46
  • TreeMap cannot be sorted by values, because it violates specification of SortedMap. See this question for available solutions https://stackoverflow.com/questions/2864840 – Bedla Apr 27 '18 at 21:52
  • Yes I did see that solution however that is ordering based upon a simple value not nested set with key? I have tried to apply that as a solution and am still having trouble as I cannot get to the key by grabbing the value that it is comparing on. I also attempted to create a KeyValuePair class and have my map and created a comparator on my key in that pair but had little success. – tw123 Apr 27 '18 at 22:14

0 Answers0