我有工作代码:
public int myFunc(int[] arr) {
Map<Integer, Integer> count = new HashMap<>();
for (int a : arr)
count.put(a, 1 + count.getOrDefault(a, 0));
PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.comparing(count::get));
// .....
}
比较器是如何看到并利用count
的?这里使用了语言的什么特征?
据我所知,如果您需要在方法(比较器)中使用变量,则该变量需要是1)方法的参数或2)在对象本身中定义或3)在全局作用域中定义。这里,count
只是一个局部变量。很明显我漏掉了什么。
Comparator. compare静态函数接受一个排序键函数,并返回包含排序键的类型的Comparator:
static <T,U extends Comparable<? super U>> Comparator<T> comparing(
Function<? super T,? extends U> keyExtractor)
传递一个方法引用,可以跨
访问https://www.baeldung.com/java-8-comparator-comparing