课程: Java Practice: Functional Programming
Solution: Transform values with a stream
- [Instructor] This challenge begins with a simple array of integer values, starting with one and going through zero. And your job is to transform those values into a single string representing a comma delimited list. Now, this is a two-step process. First, you'll need to take each integer and turn it into a string, and then you'll need to concatenate them together into a list. And here's how I did it using a bit of functional programming. Now, I'm going to start with the original code that was part of the challenge. I start with a list of strings, and then I use an explicit loop. I cast each of those values as a string and add it to the list, and then use the String.join method to turn it into a single string with commas between the values. And this code will work. That is, the challenge will return a successful message. But I wanted you to do this using functional programming. Specifically, using method references. So now I'm going to comment out this older code and I'm going to uncomment the correct code. And here's how it works. I'll need to recomment that line. And now I'll need to make one more adjustment. I'll go to this arrays class and press Control and space bar, and I'll choose that class to make sure I have the right import above. Here's how my code works. First, I'm creating a stream based on the numbers array. Then I'm calling the method mapToObj, and I'm passing in the string value of method as a method reference. That returns a stream of objects. And from there, I'll turn it into an array of strings by calling the toAarray method and passing in a new method reference, which creates a new string array. and that's the value that gets returned into the strings variable. From there, I'm doing something very similar to the old code. I'm using String.join, and I'm passing the strings array in and concatenating those together with comma separators. I'll test the code, and I'll see that once again, I get a positive response. Now, I'm going to change this code a bit. I'm going to comment this out and I'm just going to return an empty string. And I'll comment these lines out too. And now when I test my code, I'll get back a negative message. And I can change my value of show expected result to true. And I'll test my code again. And this time I see the correct string of 1, 2, 3, 4, and so on. Now I'll come back to this code and uncommon my correct solution, and remove this return of a blank string. I'll test the code again, and once again get back a positive response. So that's how I solved this challenge. Using a set of method references to cast an array of integers into a single string representing a comma delimited list.