I was wondering, how can I get the key in a TreeMap, to get that key's info? For example, I've declared a TreeMap like this:
TreeMap miniDictionary = new TreeMap<DictionaryTerm,Integer>(new TermComparator());
DictionaryTerm is just a simple class which has just two variables, "String term" and " int number".
TermComparator is a class to compare two keys:
class TermComparator implements Comparator<DictionaryTerm> {
@Override
public int compare(DictionaryTerm e1, DictionaryTerm e2) {
return e1.getTerm().compareTo(e2.getTerm());
}
}
Let's assume the TreeMap has already an entry like this: ("LedZeppelin",55) --> 25 where (LedZeppelin,55) is the key and 25 its value.
Now let's say I have this variable:
DictionaryTerm aTerm = new DictionaryTerm("LedZeppelin",100);
How can I find that "aTerm" in the TreeMap and obtain the key it to read its info? Considering that the TermComparator I created, compares by the String term.
Thanks in advcance.
I suppose you are interested in getting the key from TreeMap
that compares as equal to aTerm
, because getting the value would be easy (miniDictionary.get(aTerm)
).
For getting the key, you can use floorKey()
. This method returns "the greatest key less than or equal to the given key, or null if there is no such key", so you have to check for null and equality first:
TermComparator termComparator = new TermComparator();
TreeMap<DictionaryTerm, Integer> miniDictionary = new TreeMap<>(termComparator);
miniDictionary.put(new DictionaryTerm("LedZeppelin", 55), 25);
DictionaryTerm aTerm = new DictionaryTerm("LedZeppelin",100);
DictionaryTerm floorKey = miniDictionary.floorKey(aTerm);
if (floorKey != null && termComparator.compare(aTerm, floorKey) == 0) {
System.out.println(floorKey.getNumber()); // prints 55
}
If you want to get both key and value, use floorEntry()
.