You can do a similar thing that Collectors.joining does with String with a little helper method:
static <T> Collector<T,List<T>,List<T>> intersperse(T delim) { return Collector.of(ArrayList::new, (l,e)-> { if(!l.isEmpty()) l.add(delim); l.add(e); }, (l,l2)-> { if(!l.isEmpty()) l.add(delim); l.addAll(l2); return l; });
then you can use it similarly to Collectors.joining(delimiter) :
List<Integer> l=Stream.of(1, 2, 3).collect(intersperse(0));
produces
[1, 0, 2, 0, 3]
Please note that this is thread safe because of the collect method that protects these operations.
If you do not want to list, but insert delimiters as an intermediate stream, you can do this as follows:
Integer delimiter=0; Stream.of(1, 2, 3) .map(Stream::of) .reduce((x,y)->Stream.concat(x, Stream.concat(Stream.of(delimiter), y))) .orElse(Stream.empty())
Holger
source share