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

How can lambda expressions simplify sorting a list?

How can lambda expressions simplify sorting a list? (Computer science one · Java 8: Lambda Expressions) — "Java 8 introduced a lot of functional-style syntax,…

Ideas in this flowchart

  • Java 8 lambda expressions enable concise functional-style syntax.
  • Java 8 introduced functional-style syntax, including lambda expressions.
  • A lambda expression is an anonymous function that can be passed to methods or objects.
  • A lambda expression can sort a List according to one data field.
  • A full Comparator does not need to be constructed for this use case.
  • Example: roster.sort((a, b) -> a.getLastName().compareTo(b.getLastName()));
  • The arrow operator introduces the lambda expression syntax.
  • The lambda maps the pair (a, b) to the result of comparing their last names.
  • The comparison uses the fact that strings implement the Comparable interface.
Feed/

How can lambda expressions simplify sorting a list?

No cover

Channel

Computer science one

1 page

"Java 8 introduced a lot of functional-style syntax, including lambda expressions. Lambda expressions are essentially anonymous functions that can be passed around to other methods or objects. One use for lambda expressions is if we want to sort a List with respect to one data field, we need not build a full Comparator. Instead we can use the following syntax.\n\nList<Student> roster = ...\n\nroster.sort((a, b) -> a.getLastName().compareTo(b.getLastName()));\n\nThe new syntax is the use of the arrow operator as a lambda expression. In this case, it maps a pair, (a, b) to the value of the expression a.getLastName().compareTo(b.getLastName()) (which takes advantage of the fact that strings implement the Comparable interface)."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.