Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a keyExtractor parameter

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?

like image 789
Neminda Prabhashwara Avatar asked Sep 15 '26 16:09

Neminda Prabhashwara


2 Answers

From the documentation of Comparator#comparing(Function):

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 Note:

For example, to obtain a Comparator that compares Person objects by their last name,

Comparator<Person> byLastName = Comparator.comparing(Person::getLastName);

When you do:

Person p1 = ...;
Person p2 = ...;
int result = byLastName.compare(p1, p2);

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.


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());
  }
}

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

like image 143
Slaw Avatar answered Sep 18 '26 05:09

Slaw


From Comparator.comparing() : keyExtractor - the function used to extract the Comparable sort key

This means, it is a function to find out which parameters of the given elements, should be taken to evaluate the position between each elements

Imagine a class like

class Elt {
    int a, b;
    float c;
    public int getA() { return a; }
    public int getB() { return b; }
    public float getC() { return c; }
}

You can use several keys to compare them, a, b or c

public static void main(String[] arg) {
    List<Elt> res = Arrays.asList(new Elt(), new Elt());
    res.sort(Comparator.comparing(Elt::getA)); // elt -> elt.getA()
    res.sort(Comparator.comparing(Elt::getB)); // elt -> elt.getB()
    res.sort(Comparator.comparing(Elt::getC)); // elt -> elt.getC()
}

Comparator also allows to chain keyExtractor using thenComparing

// differentiate element with same 'c' for ex
res.sort(Comparator.comparing(Elt::getC).thenComparing(Elt::getA)); 
like image 22
azro Avatar answered Sep 18 '26 05:09

azro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!