什么是keyExtractor参数 [英] What is a keyExtractor parameter
问题描述
我正在学习 Comparator
接口,并且对它的静态 Comparator.comparing()
方法感到困惑.关于 Comparator.comparing()
方法的参数以及如何使用方法引用.当我查看文档时,它说它具有"keyExtractor参数".你能解释什么让我感到困惑吗?
I'm learning the Comparator
interface and I'm confused with it's static Comparator.comparing()
method. About Comparator.comparing()
method's parameters and how it can use method references. When I looked at the documentations it says that that it has a "keyExtractor parameter". Can you explain what is confusing me?
推荐答案
来自 接受一个函数,该函数从类型 Accepts a function that extracts a 因此,您可以根据对象的属性比较对象.相同的文档给出了一个示例: It's so you can compare objects based on a property of those objects. The same documentation gives an example: API注意: 例如,要获取一个 For example, to obtain a 当您这样做: 给定的密钥提取器将从每个 The given key extractor will extract the last name values from each 上面的 The above 其中对 Where the calls to 这篇关于什么是keyExtractor参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! T
中提取一个 Comparable
排序键,并返回一个 Comparator< T>
并按该排序进行比较键.
Comparable
sort key from a type T
, and returns a Comparator<T>
that compares by that sort key. Comparator
,该比较器将 Person
对象的姓氏进行比较,Comparator
that compares Person
objects by their last name,Comparator<Person> byLastName = Comparator.comparing(Person::getLastName);
Person p1 = ...;
Person p2 = ...;
int result = byLastName.compare(p1, p2);
Person
中提取姓氏值,以便比较这些值,而不是直接" Comparable
,则可以使用Person
in order to compare those values rather than the Person
objects "directly". If the key is not Comparable
then you can use the overload which lets you specify a Comparator
for comparing the extracted key values. byLastName
比较器将与以下内容相同:byLastName
comparator would be the same as:public class ByLastNameComparator implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
return p1.getLastName().compareTo(p2.getLastName());
}
}
p1.getLastName()
和 p2.getLastName()
的调用将是提取键 Function
的实现.p1.getLastName()
and p2.getLastName()
would be the key extractor Function
implementation.