课程: Java Practice: Functional Programming

Solution: Sort a list with a lambda expression - Java教程

课程: Java Practice: Functional Programming

Solution: Sort a list with a lambda expression

- [Instructor] Lambda expressions have all sorts of great uses, and they typically can replace more verbose declarations of complex objects in Java. In this challenge, you are asked to sort a list of objects using a comparator object that's expressed as a Lambda expression. Here's my solution to this challenge. First of all, take a look at the data that's being created at the beginning. There's a list of items, and each of these items is a kind of clothing and is associated with a price, a numeric value. That list is passed into your code, the sort list method. Here's how I wrote the code. First, I made a copy of the list. If I simply sort the value that's passed in, I'll be referring to that value and it'll be changed everywhere. And instead, I want to create a new list. And then I'm going to sort that list and return it. Then I'm calling the list sort method and passing in a comparator object, and expressing that as a Lambda expression. The Lambda expression starts off with a parameters list, and that's two items. And then after the arrow operator, it's returning an integer value that results from comparing the first item's price to the second item's price. And then it returns the result. I'll test my code, and I'll see that I get back a positive response. My list of clothing items has been sorted so that the cheapest item is at the top and the most expensive is at the bottom. Now, notice that the item class itself is declared as a member of your answer class. It could have been declared elsewhere, but this is the easiest thing for this code challenge. This is a very simple data class that has the three fields: ID, Name, and Price, and setter and getter methods for all of those fields. Now let's see what happens if I return an unsorted list. I'll comment out my code and test the code again. And this time I get a negative response. And I'll come up here and change show expected result to true. And test the code again. And now I see the expected result, which is sorted in the correct order. And as always, you can scroll sideways to see all of the returned values. Now, I'll come back here and I'll uncomment these two lines of code and run the test code again. And once again, I see that my code is correct. So that's my solution using a Lambda expression to represent a comparator object, and passing that object into the sort method of the list.

内容