Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collector returning singletonList if toList returned empty list

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?

like image 929
user3663882 Avatar asked Jul 18 '16 10:07

user3663882


People also ask

Does collectors toList () return ArrayList?

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.

What does collectors toList () do?

The toList() method of the Collectors class returns a Collector that accumulates the input elements into a new List.

What does collections singletonList?

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.

Does collector toList create new 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) .


1 Answers

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]"
like image 175
Tunaki Avatar answered Oct 10 '22 03:10

Tunaki