Java 8 maps the collection. If the collection is empty, add the default value
•
Java
I have a use case, and I must return a set containing at least 1 element The incoming collection may contain 0 or more elements
So this can be done easily
Set<ObjectB> setOfB = collectionOfA.isEmpty() ? new HashSet<ObjectB>() {{ add(new ObjectB()); }} : collectionOfA .stream() .map(item -> new ObjectB(item)) .collect(Collectors.toSet());
But
I'm also trying to take this opportunity to become more familiar with Java 8 tools and functions, so I'm trying to see if I can do it in a more Java 8 like way without conditional testing
Thank you very much for your comments and suggestions!
Solution
I think you've made it as simple as possible Remember, Java 8 is still the same language; Don't try too hard to make everything work
One of the improvements I made to your code is to use collections Singleton (New objectb()) instead of clumsy and problematic double bracket initialization
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码