Java 8 and add default if collection is empty

I have a use case in which I must return a collection with at least one element. An incoming collection may contain 0 or more elements.

therefore, it can be done quite easily.

Set<ObjectB> setOfB = collectionOfA.isEmpty() ? new HashSet<ObjectB>() {{ add(new ObjectB()); }} : collectionOfA .stream() .map(item -> new ObjectB(item)) .collect(Collectors.toSet()); 

BUT...

I am also trying to use this as an opportunity to get better acquainted with the tools and functions of Java 8, and therefore I am trying to understand whether this can be done without a conditional test and in more Java 8- as a way.

Thoughts and suggestions are welcome!

+5
source share
2 answers

I think you already got it as easy as possible. Remember that Java 8 is still the same language; Do not overdo it, trying to make everything workable.

The only thing I would do for your code is to use Collections.singleton(new ObjectB()) instead of the awkward and problematic dual-binding initialization.

+4
source

You will need to have a condition, because the counter is available only when the reduction operation is called. However, for a set of single elements, you can:

 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()) 
+3
source

Source: https://habr.com/ru/post/1242317/


All Articles