java comparator comparing

java comparator comparing

The comparing method is a static utility method in the Comparator interface in Java that allows you to create a comparator based on a specific key extracted from the elements being compared. It takes a Function as an argument, which is a functional interface that defines a method for extracting the key from an element. The Function is applied to each element in the stream, and the resulting values are used for comparison.

Here is an example of how to use the comparing method to create a comparator that compares Person objects based on their last names:

ref‮ual:ot re‬tturi.com
import java.util.Comparator;

public class Main {
  public static void main(String[] args) {
    // Create a list of Person objects
    List<Person> people = Arrays.asList(
      new Person("Alice", "Smith"),
      new Person("Bob", "Johnson"),
      new Person("Charlie", "Smith")
    );

    // Create a comparator that compares Person objects by last name
    Comparator<Person> lastNameComparator = Comparator.comparing(Person::getLastName);

    // Sort the list of Person objects using the comparator
    people.sort(lastNameComparator);

    // Print the sorted list
    for (Person person : people) {
      System.out.println(person.getLastName() + ", " + person.getFirstName());
    }
  }
}

class Person {
  private String firstName;
  private String lastName;

  public Person(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  public String getFirstName() {
    return firstName;
  }

  public String getLastName() {
    return lastName;
  }
}

This example creates a list of Person objects and a comparator that compares them by their last names. The list is then sorted using the comparator, and the sorted list is printed to the console. The output of this example would be:

Johnson, Bob
Smith, Alice
Smith, Charlie
Created Time:2017-11-03 00:14:51  Author:lautturi