课程: Java Practice: Functional Programming

Solution: Inspect a collection - Java教程

课程: Java Practice: Functional Programming

Solution: Inspect a collection

- This challenge starts with a data set a list of items where each item has an ID, a name, a price, and a quantity. Your job in the challenge is to calculate the total value of the shopping cart using functional programming. Here's my solution to the challenge. In my getCartTotal method, I'm starting by wrapping the value of zero inside an instance of atomic reference. I'm doing this because I'm going to be passing this value into a lambda expression, and if I simply try to pass a primitive value, say a float or an int, or even one of the wrapper objects, like Float with an uppercase F into the lambda, I won't be able to modify it because that value would have to be marked as final. So I wrap that value inside an atomic reference object and that object will be final, but the value in it can be updated. Now I'm receiving a list of items and I need to iterate through that list, so I'm going to call the forEach method. This method accepts a lambda expression. I take the item, which is the object with all of the values and I pass it into the lambda expression, and from there I'm using a method named updateAndGet. The lambda expression passes in the value and then adds to it by multiplying the quantity and the price of the current item. Once the loop is complete, I have a total object, which is again the atomic reference, and I can get its wrapped value by calling the get method, and that's what I'm returning. I'll test my code to see how I did, and I get back a positive response and a total value of 10,100. Now let's see what happens if I comment this line out, and now I'll be returning a value of zero 'cause I'm never operating on any of those items. I'll click the test code and I get back a negative message. And as always with these code challenges, I can change the value of showExpectedResult to true, test my code again, and then I'll see the expected value, and then I'll uncomment that line of code, and my code will once again be intact, successfully looping through the values, and adding them together to get the total value of the shopping cart. That's how I solved this challenge. How did your code compare?

内容