例如,请参见以下函数,该函数在流中复制偶数:
Stream<Integer> duplicateEvens(Stream<Integer> items) {
return items.flatMap(i -> {
if (i % 2 == 0) {
return Stream.of(i, i);
} else {
return Stream.of(i);
}
}
}
另一种方法可能是使用流生成器,如下所示:
Stream<Integer> duplicateEvens(Stream<Integer> items) {
Stream.Builder result = builder();
Stream<Integer> extra = items.peek(result.add(i))
.filter(i -> i%2 == 0);
return Stream.concat(result.build(), extra);
}