I have quite a large stream pipeline and therefore would like to keep it clean. I have the following part of larger pipeline
Integer defaultInt;
//...
Stream<Integer> ints;
ints.filter(/* predicate_goes_here */).collect(toSingletonIfEmptyCollector);
Where toSingletonIfEmptyCollector
is supposed to act the same as Collectors.toList()
does if it returns non-emtpy list and Collections.singletonList(defaultInt)
if Collectors.toList()
returned empty.
Is there a shorter way to implement it (e.g. by composing standard collectors provided in JDK) rather then implementing all Collector
's method from scratch?
For instance, Collectors. toList() method can return an ArrayList or a LinkedList or any other implementation of the List interface. To get the desired Collection, we can use the toCollection() method provided by the Collectors class.
The toList() method of the Collectors class returns a Collector that accumulates the input elements into a new List.
The singletonList() method of java. util. Collections class is used to return an immutable list containing only the specified object. The returned list is serializable. This list will always contain only one element thus the name singleton list.
toList. Returns a Collector that accumulates the input elements into a new List . There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; if more control over the returned List is required, use toCollection(Supplier) .
You can use collectingAndThen
and perform an additional finisher operation on the built-in toList()
collector that will return a singleton list in case there was no elements.
static <T> Collector<T, ?, List<T>> toList(T defaultValue) {
return Collectors.collectingAndThen(
Collectors.toList(),
l -> l.isEmpty() ? Collections.singletonList(defaultValue) : l
);
}
It would be used like this:
System.out.println(Stream.of(1, 2, 3).collect(toList(5))); // prints "[1, 2, 3]"
System.out.println(Stream.empty().collect(toList(5))); // prints "[5]"
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