Bifalgorithm post · Computer science one · Java 8: Lambda Expressions

How can method references and Comparator methods make ordering more concise?

How can method references and Comparator methods make ordering more concise? (Computer science one · Java 8: Lambda Expressions) — "We can make this even more…

Ideas in this flowchart

  • Java 8 enables concise, flexible list sorting with Comparator features.
  • Method references make sorting expressions more terse.
  • Getters can be used as key extractors in a chained Comparator.
  • The list is sorted with myList.sort and Comparator.comparing.
  • The primary sorting key is Student::getLastName.
  • The first tie-breaker is Student::getFirstName.
  • The second tie-breaker is Student::getGpa.
  • The updated Comparator interface provides additional convenience methods.
  • The reversed() method returns a Comparator with reversed ordering.
  • The static nullsFirst() and nullsLast() methods control the ordering of null values.
Feed/

How can method references and Comparator methods make ordering more concise?

No cover

Channel

Computer science one

1 page

"We can make this even more terse using method references, another new feature in Java 8.\n\n//using getters as key extractors\n\nmyList.sort(\n\nComparator.comparing(Student::getLastName)\n\n.thenComparing(Student::getFirstName)\n\n.thenComparing(Student::getGpa));\n\nThere are several other convenient methods provided by the updated Comparator interface. For example, the reversed() member method returns a new Comparator that defines the reversed order. The static methods, nullsFirst() and nullsLast() can be used to modify a Comparator to order null values."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.