下面列出了java.util.stream.Collector#of ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static Collector<ByteBuf, ByteBufQueue, ByteBuf> collector(int maxSize) {
return Collector.of(
ByteBufQueue::new,
(queue, buf) -> {
int size = buf.readRemaining();
if (size > maxSize || queue.hasRemainingBytes(maxSize - size + 1)) {
queue.recycle();
buf.recycle();
throw new UncheckedException(new InvalidSizeException(ByteBufQueue.class,
"ByteBufQueue exceeds maximum size of " + maxSize + " bytes"));
}
queue.add(buf);
},
(bufs1, bufs2) -> {
throw new UnsupportedOperationException("Parallel collection of byte bufs is not supported");
},
ByteBufQueue::takeRemaining);
}
@Override
public Collector<Schema.Entry, Record.Builder, Record> toRecord(final Schema schema, final Record fallbackRecord,
final BiFunction<Schema.Entry, Record.Builder, Boolean> customHandler,
final BiConsumer<Record.Builder, Boolean> beforeFinish) {
final AtomicBoolean customHandlerCalled = new AtomicBoolean();
return Collector.of(() -> recordBuilderFactory.newRecordBuilder(schema), (builder, entry) -> {
if (!customHandler.apply(entry, builder)) {
forwardEntry(fallbackRecord, builder, entry.getName(), entry);
} else {
customHandlerCalled.set(true);
}
}, (b1, b2) -> {
throw new IllegalStateException("merge unsupported");
}, builder -> {
beforeFinish.accept(builder, customHandlerCalled.get());
return builder.build();
});
}
/**
* Build a collector for transforming rows to a {@link io.vertx.core.json.JsonArray} with specific types.
*
* @param rowMapper mapper to transform a row
* @param <T> the target type
* @return the collector
*/
public static <T> Collector<Row, ?, JsonArray> jsonArrayCollector(Function<Row, T> rowMapper) {
return Collector.of(JsonArray::new,
(jsonArray, row) -> jsonArray.add(rowMapper.apply(row)),
(left, right) -> {
left.addAll(right);
return left;
}, Collector.Characteristics.IDENTITY_FINISH);
}
public static <T> Collector<T, LinkedHashSet<T>, LinkedHashSet<T>> toLinkedHashSet() {
return Collector.of(
LinkedHashSet::new,
HashSet::add,
(a1, a2) -> {
LinkedHashSet<T> results = new LinkedHashSet<T>();
results.addAll(a1);
results.addAll(a2);
return results;
},
ts -> ts
);
}
public static <T, A, R> Collector<T, A, R> excluding(Predicate<T> predicate, Collector<T, A, R> collector) {
return Collector.of(
collector.supplier(),
(s, t) -> {
if(predicate.negate().test(t)) {
collector.accumulator().accept(s, t);
}
},
collector.combiner(),
collector.finisher(),
setToArray(collector.characteristics())
);
}
/**
* Collect elements into a new list (using a @code{ListBuffer})
*/
public static <Z> Collector<Z, ListBuffer<Z>, List<Z>> collector() {
return Collector.of(ListBuffer::new,
ListBuffer::add,
(buf1, buf2)-> { buf1.addAll(buf2); return buf1; },
ListBuffer::toList);
}
public static <T, K, V> Collector<T, ?, ImmutableBiMap<K, V>> toBiMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper) {
return Collector.of(
ImmutableBiMap.Builder<K, V>::new,
(builder, input) -> builder.put(keyMapper.apply(input), valueMapper.apply(input)),
(l, r) -> l.putAll(r.build()),
ImmutableBiMap.Builder::build
);
}
/**
* Returns a collector that collects items in a Morpheus array
* @param type the array type
* @param expectedLength an estimate of the expected length, does not have to be exact
* @param <T> the array element type
* @return the newly created collector
*/
public static <T> Collector<T,ArrayBuilder<T>,Array<T>> toArray(Class<T> type, int expectedLength) {
final Supplier<ArrayBuilder<T>> supplier = () -> ArrayBuilder.of(expectedLength, type);
final BinaryOperator<ArrayBuilder<T>> combiner = ArrayBuilder::addAll;
final BiConsumer<ArrayBuilder<T>,T> accumulator = ArrayBuilder::add;
final Function<ArrayBuilder<T>,Array<T>> finisher = ArrayBuilder::toArray;
return Collector.of(supplier, accumulator, combiner, finisher);
}
public static <T, A, R> Collector<T, A, R> including(Predicate<T> predicate, Collector<T, A, R> collector) {
return Collector.of(
collector.supplier(),
(s, t) -> {
if(predicate.test(t)) {
collector.accumulator().accept(s, t);
}
},
collector.combiner(),
collector.finisher(),
setToArray(collector.characteristics())
);
}
/** Creates a {@link Row} from the list of values and {@link #getSchema()}. */
public static <T> Collector<T, List<Object>, Row> toRow(Schema schema) {
return Collector.of(
() -> new ArrayList<>(schema.getFieldCount()),
List::add,
(left, right) -> {
left.addAll(right);
return left;
},
values -> Row.withSchema(schema).addValues(values).build());
}
/**
* Returns the java type of the column named "t".
* @param clazz type of element to fetch
* @param <T> returning type
* @return a collector
*/
public static <T> Collector<Result.RowColumn, Class<T>[], Class<T>> javaTypeCollector(Class<T> clazz) {
return Collector.of(
() -> new Class[1],
(a, r) -> a[0] = r.at("t").javaType(),
(l, r) -> null,
a -> a[0]);
}
public static <T> Collector<T, RefBoolean, Boolean> toNone(Predicate<T> predicate) {
return Collector.of(
() -> new RefBoolean(true),
(a, t) -> a.value &= !predicate.test(t),
(a1, a2) -> {
a1.value &= a2.value;
return a1;
},
b -> b.value);
}
public static <X> Collector<X, ?, Stream<X>> toDuplicateStream(int min) {
if (min < 2) {
throw new IllegalArgumentException();
}
Supplier<Map<X, Integer>> supplier = HashMap::new;
BiConsumer<Map<X, Integer>, X> accumulator = (map, key) -> map.merge(key, 1, Integer::sum);
BinaryOperator<Map<X, Integer>> combiner = Functions.mergeToLeftMap(Integer::sum);
Function<Map<X, Integer>, Stream<X>> finisher = Functions.keyStreamWhereValues(v -> v >= min);
return Collector.of(supplier, accumulator, combiner, finisher, Characteristics.UNORDERED);
}
static <T> Collector<T, ?, TinyContainer<T>> toTinyContainer() {
return Collector.of(TinyContainer::new, TinyContainer::add, TinyContainer::addAll);
}
public static <T> Collector<T, ?, ImmutableList<T>> toImmutableList() {
return Collector.of(ImmutableList::builder, Builder::add,
(b1, b2) -> { b1.addAll(b2.build()); return b2; },
ImmutableList.Builder<T>::build);
}
/**
* of MonetaryAmount group by MonetarySummary
* @return the MonetarySummaryStatistics
*/
public static Collector<MonetaryAmount,GroupMonetarySummaryStatistics,GroupMonetarySummaryStatistics>
groupBySummarizingMonetary(){
return Collector.of(GroupMonetarySummaryStatistics::new, GroupMonetarySummaryStatistics::accept,
GroupMonetarySummaryStatistics::combine);
}
/**
* Collector used at the end of a stream to build an immutable sorted set.
* <p>
* A collector is used to gather data at the end of a stream operation.
* This method returns a collector allowing streams to be gathered into
* an {@link ImmutableSet}.
*
* @param <T> the type of element in the sorted set
* @param comparator the comparator
* @return the immutable sorted set collector
*/
public static <T> Collector<T, ImmutableSortedSet.Builder<T>, ImmutableSortedSet<T>>
toImmutableSortedSet(Comparator<? super T> comparator) {
return Collector.of(
(Supplier<ImmutableSortedSet.Builder<T>>) () -> new ImmutableSortedSet.Builder<>(comparator),
ImmutableSortedSet.Builder<T>::add,
(l, r) -> l.addAll(r.build()),
ImmutableSortedSet.Builder<T>::build,
Collector.Characteristics.UNORDERED);
}
/**
* Collects elements matching the given type, into a collection provided
* by the given supplier.
*
* <pre>
* {@code
* List<RcsMessage> results = Stream.of(new RcsMessage(1), new SmsMessage(2), new MmsMessage(3))
* .collect(CollectorOps.typedCollector(RcsMessage.class, ArrayList::new));
* }
* </pre>
*
* @param clazz the type of element to collect
* @param supplier a supplier for this collector, generally a method reference to a collections object constructor, such as ArrayList::new
* @param <T> the type of input elements to the reduction operation
* @param <S> the type of output elements in the resulting collection
* @param <R> the collection supplied by the supplier
* @return a new collection of the elements that were instances of S
*/
public static <T, S extends T, R extends Collection<S>> Collector<T, ?, R> typedCollector(Class<S> clazz, Supplier<R> supplier) {
return Collector.of(
supplier,
(R collection, T o) -> {
if (clazz.isInstance(o)) {
collection.add(clazz.cast(o));
}
},
(R r1, R r2) -> { r1.addAll(r2); return r1; },
IDENTITY_FINISH
);
}
/**
* Collector used at the end of a stream to build an immutable list.
* <p>
* A collector is used to gather data at the end of a stream operation.
* This method returns a collector allowing streams to be gathered into
* an {@link ImmutableList}.
*
* @param <T> the type of element in the list
* @return the immutable list collector
*/
public static <T> Collector<T, ImmutableList.Builder<T>, ImmutableList<T>> toImmutableList() {
return Collector.of(
ImmutableList.Builder<T>::new,
ImmutableList.Builder<T>::add,
(l, r) -> l.addAll(r.build()),
ImmutableList.Builder<T>::build);
}
/**
* A {@link Collector} that collects a {@link Stream} of {@link Value}s into a {@link Value}
* of a {@link List}.
*
* <p>The semantics of joining {@link Value}s is decided by this {@link EvalContext}.
*
* @param context The context which values are processed in
* @param <T> The inner type of the values
* @return A collector for a stream of values
*/
public static <T> Collector<Value<T>, ?, Value<List<T>>> toValueList(EvalContext context) {
return Collector.of(
ArrayList::new, List::add, (a, b) -> { a.addAll(b); return a; },
ValueFold.inContext(context));
}