Concept
How can lambda expressions simplify sorting a list?
ComputerScienceOne / Java 8: Lambda Expressions
"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)."
Related Ideas
- How can method references and Comparator methods make ordering more concise?ComputerScienceOne · Java 8: Lambda Expressions
- How can anonymous classes define custom Java comparators?ComputerScienceOne · Comparators
- How does Java sort arrays and lists with comparators?ComputerScienceOne · Sorted Collections
- How do the Arrays and Collections classes sort elements?ComputerScienceOne · Sorting
- How can Comparator order Student objects by different fields?ComputerScienceOne · Comparators
- What is the difference between Comparable and Comparator in Java?ComputerScienceOne · Comparators
- How can a Java Comparator handle null values?ComputerScienceOne · Importance of javaequals() and javahashCode() Methods
- How can you sort lists and arrays of students in Java?ComputerScienceOne · Handling javanull values