Sri
Sri

Reputation: 613

Comparator using Lambdas

I have a comparator which checks if any of the string is null and returns -1. If they are not null, it then does the comparison. I want to have this implemented using lambda functions.

Here is the code:

private SortedSet<Student> studentSet() {
  return new TreeSet<>(new Comparator<Student>() {
   @Override
   public int compare(Student s1, Student s2) {
     if(s1.getName() == null) {
       return -1;
     }
     if(s2.getName() == null) {
       return 1;
     }
     return s1.getName().compareToIgnoreCase(s2.getName());
    }
   });
 }

I know how to return for a simple comparator using lambdas. I'm confused on how to implement the above code.

Upvotes: 0

Views: 359

Answers (1)

Jeffrey
Jeffrey

Reputation: 44808

There are a couple ways to do this. The literal translation of your code to a lambda is

Comparator<Student> cmp = (s1, s2) -> {
  if (s1.getName() == null) {
    return -1;
  }
  if (s2.getName() == null) {
    return 1;
  }

  return s1.getName().compareToIgnoreCase(s2.getName());
};

The one-liner equivalent (using Comparator::comparing and Comparator::nullsFirst) is

Comparator<Student> cmp = Comparator.comparing(Student::getName,
      Comparator.nullsFirst(String.CASE_INSENSITIVE_ORDER));

Upvotes: 10

Related Questions