什么是keyExtractor参数 [英] What is a keyExtractor parameter

查看:67
本文介绍了什么是keyExtractor参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 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?

推荐答案

来自

接受一个函数,该函数从类型 T 中提取一个 Comparable 排序键,并返回一个 Comparator< T> 并按该排序进行比较键.

Accepts a function that extracts a Comparable sort key from a type T, and returns a Comparator<T> that compares by that sort key.

因此,您可以根据对象的属性比较对象.相同的文档给出了一个示例:

It's so you can compare objects based on a property of those objects. The same documentation gives an example:

API注意:

例如,要获取一个 Comparator ,该比较器将 Person 对象的姓氏进行比较,

For example, to obtain a 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 ,则可以使用

The given key extractor will extract the last name values from each 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 比较器将与以下内容相同:

The above 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 的实现.

Where the calls to p1.getLastName() and p2.getLastName() would be the key extractor Function implementation.

这篇关于什么是keyExtractor参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆