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;
}