课程: Java Practice: Functional Programming

Solution: Do math with lambda expressions - Java教程

课程: Java Practice: Functional Programming

Solution: Do math with lambda expressions

- [Instructor] This challenge asks you to create a simple calculator application and to execute four mathematical operations against two values that are being passed in. The test code section shows that you have values of 10 and 20 and that these are being passed into the calculate method. Now, I'll scroll down in my answer section and show you my solution. To create this calculator, I'm creating four instances of the BiFunction interface. This interface takes three generic declarations. These are the data types of the values. The first two types are for the values being passed in and the third type is for the value that's being returned. Each of these BiFunction objects has a name and I've just used names indicating what mathematical operations they represent and then they're assigned to lambda expressions. Each lambda expression starts off with an arguments list, and then after the arrow operator, it returns to the results of a mathematical operation. To use these objects, I'm passing them into a map object, associating them with these constants that were already declared. And then for each of the BiFunction objects, I'm calling the apply method and passing in the two values. When I test my code, I get back a positive response. And remember that for these long strings, you can scroll sideways to see everything. Now I'm going to change this, so my answer is incorrect. Instead of the add object, I'll use the subtract object. I'll test my code again, and this time, I see that the answer's wrong. I once again can see the values that I returned, but then I can see the expected result by changing this value to true and running the code again. And this time, I can see both the values that my code returned and the expected values, and notice that the values for the ad operation are different. So now I'll go back and change my value again. Once again, I'll use the ad object here, and run the code again, and this time, it comes back with a positive response. So that's how I solved this challenge. Compare it to your code and see what you might have done differently. As always, there's more than one way to get back the correct result. I used BiFunction objects and lambda expressions. What did you use?

内容