课程: Java Practice: Exception Handling
Solution: Unsupported Operation
- [Instructor] Here is my solution to the challenge. And of course, there are multiple ways to solve this challenge, and if you came up with a different one, that is always great. So what we're doing here is we want to be able to return a list that is what is passed in as items minus the value in toRemove. Now, one way to do this is to actually change the type of list to a linked list and use an iterator so you can actually remove the item using the iterator. And that is certainly a valid solution. Another way to do this is to think about it differently. What do we actually want? Do we need to modify the list or do we just need to return the appropriate string? If we view it from the perspective of what actually needs to be returned, then we could simply use a stream to handle the job. So we can do items.stream.filter, and then we could just say, keep in everything unless it matches toRemove. Like this. After that, I'll put collect. Remember, we can't just make it into a list because that's a later Java feature, and this coder pad uses Java 11. So we're going to do collectors.toList and then we'll call toString at the end. And that's it. We just filter that list that's passed in, taking out toRemove. Hit Test My Code, and you should see the successful result in the console output window. If you want to change this to test the other ones, you can change it to item two, and then you should see that item two is removed. And you could change it to item three as well just for fun. The main thing to take away from this challenge is sometimes thinking about the result in a different way can help you come up with a different solution. It may be better or it may not be better, but it may help when you're trying to solve these coding challenges.