Note that you can access a final variable from an anonymous inner class, and you can use this for your need.
Here is a simple example:
public static void main(String args[]) {
final Map<String,Integer> map = new HashMap<>();
String s1 = "a";
String s2 = "b";
String s3 = "c";
map.put(s2, 1);
map.put(s1, 2);
map.put(s3, 3);
PriorityQueue<String> pq = new PriorityQueue<>(3, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return map.get(o1).compareTo(map.get(o2));
}
});
pq.add(s1);
pq.add(s2);
pq.add(s3);
while (pq.isEmpty() == false)
System.out.println(pq.poll());
}
Note that the Comparator object is using the map local variable. It can be done because the variable map was declared final.
An alternative is passing a reference to the Map in the constructor of the Comparator (if it is not an anonymous inner class), store it as a field and use it later on.
In any case - you must make sure the data in the Map for some element does not change after the element was inserted to the PriorityQueue - if it happens - your data structure will become corrupted and you will get an undefined behavior.
HashMapobject in the constructor (and later as a member) of theComparator? Or as an alternative - if theComparatoris an anonymous inner class - you can accessfinalvariables from the method it was created.