I've got a use case where I must return a collection with at least 1 element. The incoming collection may have 0 or more elements.
so this could be done fairly 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 use this as a chance to better familiarize myself with the Java 8 tools and features, and so i'm trying to see if this can be done without the conditional test and in a more Java 8-like way.
Thoughts and suggestions are most appreciated!
Get the map with null values and the default value to be replaced with. Get the set view of the Map using Map.entrySet () method. Convert the obtained set view into stream using stream () method. Now map the null values to default value with the help of map () method. Collect the modified stream into Map using collect () method.
Overview of Map Collection A Map is an object that maps keys to values, or is a collection of attribute-value pairs. It models the function abstraction in mathematics. The following picture illustrates a map: Note that a Map is not considered to be a true collection, as the Map interface does not extend the Collection interface.
You had to iterate through List using a for loop or foreach loop and transform each element. In Java 8, you get the stream, which allows you to apply many functional programming operators like the map, reduce, and filter. By using the map () function, you can apply any function to every element of the Collection.
@ColinD True. When using apache commons, we can use DefaultedMap, which returns a default value when the map does not contain the specified value. Guava's computing map concept was superseded with LoadingCache. Also java 8 introduced to Map interface nice computeIfAbsent default method which doesn't break map contract and features lazy evaluation .
I think you've already got it pretty much as simple as possible. Remember that Java 8 is still the same language; don't overdo trying to make everything functional.
The one improvement I would make to your code would be to use Collections.singleton(new ObjectB())
instead of the awkward and problematic double-brace initialization.
You'll have to have a condition since the count is only available when you call a reduction operation. However, for the single element set you can do:
Set<ObjectB> setOfB = collectionOfA.isEmpty() ?
Stream.of(new ObjectB()).collect(Collectors.toSet()) :
collectionOfA
.stream()
.map(item -> new ObjectB(item))
.collect(Collectors.toSet());
which can be reduced to
Set<ObjectB> setOfB = ( collectionOfA.isEmpty() ?
Stream.of(new ObjectB()) :
collectionOfA.stream().map(item -> new ObjectB(item)) )
.collect(Collectors.toSet())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With