Example usage for java.util.stream Collector of

List of usage examples for java.util.stream Collector of

Introduction

In this page you can find the example usage for java.util.stream Collector of.

Prototype

public static <T, R> Collector<T, R, R> of(Supplier<R> supplier, BiConsumer<R, T> accumulator,
        BinaryOperator<R> combiner, Characteristics... characteristics) 

Source Link

Document

Returns a new Collector described by the given supplier , accumulator , and combiner functions.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    List<Person> persons = Arrays.asList(new Person("Max", 18), new Person("Peter", 23),
            new Person("Pamela", 23), new Person("David", 12));

    Collector<Person, StringJoiner, String> personNameCollector = Collector.of(() -> new StringJoiner(" | "), // supplier
            (j, p) -> j.add(p.name.toUpperCase()), // accumulator
            (j1, j2) -> j1.merge(j2), // combiner
            StringJoiner::toString); // finisher

    String names = persons.stream().collect(personNameCollector);

    System.out.println(names);//from   w w  w.j a  v a 2 s.  co  m
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    List<Person> persons = Arrays.asList(new Person("Max", 18), new Person("Peter", 23),
            new Person("Pamela", 23), new Person("David", 12));

    Collector<Person, StringJoiner, String> personNameCollector = Collector.of(() -> {
        System.out.println("supplier");
        return new StringJoiner(" | ");
    }, (j, p) -> {//from w ww .ja  v a  2  s.  c  o  m
        System.out.format("accumulator: p=%s; j=%s\n", p, j);
        j.add(p.name.toUpperCase());
    }, (j1, j2) -> {
        System.out.println("merge");
        return j1.merge(j2);
    }, j -> {
        System.out.println("finisher");
        return j.toString();
    });

    String names = persons.stream().collect(personNameCollector);

    System.out.println(names);
}

From source file:Main.java

public static <E> Collector<Optional<E>, Collection<E>, Stream<E>> filterEmpty() {
    return Collector.of(ConcurrentLinkedQueue::new, (q, oe) -> oe.ifPresent(q::add), (q1, q2) -> {
        q1.addAll(q2);//www .  ja  va2  s .  co  m
        return q1;
    }, Collection::stream);
}

From source file:de.metas.ui.web.process.json.JSONDocumentActionsList.java

public static final Collector<WebuiRelatedProcessDescriptor, ?, JSONDocumentActionsList> collect(
        final JSONOptions jsonOpts) {
    final Supplier<List<WebuiRelatedProcessDescriptor>> supplier = ArrayList::new;
    final BiConsumer<List<WebuiRelatedProcessDescriptor>, WebuiRelatedProcessDescriptor> accumulator = List::add;
    final BinaryOperator<List<WebuiRelatedProcessDescriptor>> combiner = (l, r) -> {
        l.addAll(r);//from  w  w w  . ja v a  2  s.c o  m
        return l;
    };
    final Function<List<WebuiRelatedProcessDescriptor>, JSONDocumentActionsList> finisher = processDescriptors -> new JSONDocumentActionsList(
            processDescriptors, jsonOpts);
    return Collector.of(supplier, accumulator, combiner, finisher);
}

From source file:de.metas.ui.web.window.datatypes.json.JSONLookupValuesList.java

public static final Collector<JSONLookupValue, ?, JSONLookupValuesList> collect() {
    final Supplier<List<JSONLookupValue>> supplier = ArrayList::new;
    final BiConsumer<List<JSONLookupValue>, JSONLookupValue> accumulator = List::add;
    final BinaryOperator<List<JSONLookupValue>> combiner = (l, r) -> {
        l.addAll(r);//from www.  ja v  a  2  s. c o m
        return l;
    };
    final Function<List<JSONLookupValue>, JSONLookupValuesList> finisher = JSONLookupValuesList::ofJSONLookupValuesList;
    return Collector.of(supplier, accumulator, combiner, finisher);
}

From source file:com.github.steveash.guavate.Guavate.java

/**
 * Collector used at the end of a stream to build an immutable list.
 * <p>//w  w  w  . j a va 2 s  .co  m
 * 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);
}

From source file:com.ikanow.aleph2.shared.crud.mongodb.utils.MongoDbUtils.java

/** Creates a big $and/$or list of the list of fields in the single query component
 * @param andVsOr - top level MongoDB operator
 * @param query_in - a single query (ie set of fields)
 * @return the MongoDB query object (no meta - that is added above)
 *//*from  ww  w .  ja  v  a2s.  c o m*/
protected static <T> DBObject convertToMongoQuery_single(final String andVsOr,
        final SingleQueryComponent<T> query_in) {
    final LinkedHashMultimap<String, Tuple2<Operator, Tuple2<Object, Object>>> fields = query_in.getAll();

    // The actual query:

    return Patterns.match(fields).<DBObject>andReturn().when(f -> f.isEmpty(), f -> new BasicDBObject())
            .otherwise(f -> f.asMap().entrySet().stream()
                    .<Tuple2<String, Tuple2<Operator, Tuple2<Object, Object>>>>flatMap(
                            entry -> entry.getValue().stream()
                                    .map(val -> Tuples._2T(entry.getKey(),
                                            Tuples._2T(val._1(), removeEnums(val._2())))))
                    .collect(Collector.of(BasicDBObject::new, (acc, entry) -> {
                        Patterns.match(acc.get(andVsOr)).andAct().when(l -> (null == l), l -> {
                            BasicDBList dbl = new BasicDBList();
                            dbl.add(operatorToMongoKey(entry._1(), entry._2()));
                            acc.put(andVsOr, dbl);
                        }).when(BasicDBList.class, l -> l.add(operatorToMongoKey(entry._1(), entry._2())))
                                .otherwise(() -> {
                                });
                    }, (a, b) -> {
                        a.putAll(b.toMap());
                        return a;
                    }, Characteristics.UNORDERED)));
}

From source file:com.ikanow.aleph2.shared.crud.mongodb.utils.MongoDbUtils.java

/** Create a MongoDB update object
 * @param update - the generic specification
 * @param add increments numbers or adds to sets/lists
 * @param remove decrements numbers of removes from sets/lists
 * @return the mongodb object/* w  w  w.java 2s .com*/
 * @throws IOException 
 * @throws JsonMappingException 
 * @throws JsonGenerationException 
 */
@SuppressWarnings("unchecked")
public static <O> DBObject createUpdateObject(final UpdateComponent<O> update) {
    final ObjectMapper object_mapper = MongoJackModule
            .configure(BeanTemplateUtils.configureMapper(Optional.empty()));

    return update.getAll().entries().stream()
            .map(kv -> Patterns
                    .match(kv.getValue()._2()).<Map.Entry<String, Tuple2<UpdateOperator, Object>>>andReturn()
                    // Special case, handle bean template
                    .when(e -> null == e, __ -> kv)
                    .when(e -> e instanceof Enum,
                            e -> Maps.immutableEntry(kv.getKey(), Tuples._2T(kv.getValue()._1(), e.toString())))
                    .when(JsonNode.class,
                            j -> Maps.immutableEntry(kv.getKey(),
                                    Tuples._2T(kv.getValue()._1(), convertJsonBean(j, object_mapper))))
                    .when(BeanTemplate.class,
                            e -> Maps.immutableEntry(kv.getKey(),
                                    Tuples._2T(kv.getValue()._1(), convertBeanTemplate(e, object_mapper))))
                    // Special case, handle list of bean templates
                    .when(Collection.class, l -> !l.isEmpty() && (l.iterator().next() instanceof JsonNode),
                            l -> Maps.immutableEntry(kv.getKey(),
                                    Tuples._2T(kv.getValue()._1(),
                                            l.stream().map(j -> convertJsonBean((JsonNode) j, object_mapper))
                                                    .collect(Collectors.toList()))))
                    .when(Collection.class, l -> !l.isEmpty() && (l.iterator().next() instanceof BeanTemplate),
                            l -> Maps.immutableEntry(kv.getKey(), Tuples._2T(kv.getValue()._1(), l.stream()
                                    .map(e -> convertBeanTemplate((BeanTemplate<Object>) e, object_mapper))
                                    .collect(Collectors.toList()))))
                    .otherwise(() -> kv))
            .collect(Collector.of(BasicDBObject::new, (acc, kv) -> {
                Patterns.match(kv.getValue()._2()).andAct()
                        // Delete operator, bunch of things have to happen for safety
                        .when(o -> ((UpdateOperator.unset == kv.getValue()._1()) && kv.getKey().isEmpty()
                                && (null == kv.getValue()._2())), o -> acc.put("$unset", null))
                        //Increment
                        .when(Number.class, n -> (UpdateOperator.increment == kv.getValue()._1()),
                                n -> nestedPut(acc, "$inc", kv.getKey(), n))
                        // Set
                        .when(o -> (UpdateOperator.set == kv.getValue()._1()),
                                o -> nestedPut(acc, "$set", kv.getKey(), o))
                        // Unset
                        .when(o -> (UpdateOperator.unset == kv.getValue()._1()),
                                o -> nestedPut(acc, "$unset", kv.getKey(), 1))
                        // Add items/item to list
                        .when(Collection.class, c -> (UpdateOperator.add == kv.getValue()._1()),
                                c -> nestedPut(acc, "$push", kv.getKey(), new BasicDBObject("$each", c)))
                        .when(o -> (UpdateOperator.add == kv.getValue()._1()),
                                o -> nestedPut(acc, "$push", kv.getKey(), o))
                        // Add item/items to set
                        .when(Collection.class, c -> (UpdateOperator.add_deduplicate == kv.getValue()._1()),
                                c -> nestedPut(acc, "$addToSet", kv.getKey(), new BasicDBObject("$each", c)))
                        .when(o -> (UpdateOperator.add_deduplicate == kv.getValue()._1()),
                                o -> nestedPut(acc, "$addToSet", kv.getKey(), o))
                        // Remove items from list by query
                        .when(QueryComponent.class, q -> (UpdateOperator.remove == kv.getValue()._1()),
                                q -> nestedPut(acc, "$pull", kv.getKey(), convertToMongoQuery(q)._1()))
                        // Remove items/item from list
                        .when(Collection.class, c -> (UpdateOperator.remove == kv.getValue()._1()),
                                c -> nestedPut(acc, "$pullAll", kv.getKey(), c))
                        .when(o -> (UpdateOperator.remove == kv.getValue()._1()),
                                o -> nestedPut(acc, "$pullAll", kv.getKey(), Arrays.asList(o)))
                        .otherwise(() -> {
                        }); // (do nothing)
            }, (a, b) -> {
                a.putAll(b.toMap());
                return a;
            }, Characteristics.UNORDERED));
}

From source file:com.ikanow.aleph2.data_model.utils.TestCrudUtils.java

/** Create a MongoDB update object
 * @param update - the generic specification
 * @param add increments numbers or adds to sets/lists
 * @param remove decrements numbers of removes from sets/lists
 * @return the mongodb object//from w w w  .ja  va 2 s .c  om
 * @throws IOException 
 * @throws JsonMappingException 
 * @throws JsonGenerationException 
 */
@SuppressWarnings("unchecked")
public static <O> DBObject createUpdateObject(final UpdateComponent<O> update) {
    final ObjectMapper object_mapper = MongoJackModule
            .configure(BeanTemplateUtils.configureMapper(Optional.empty()));

    return update.getAll().entries().stream()
            .map(kv -> Patterns
                    .match(kv.getValue()._2()).<Map.Entry<String, Tuple2<UpdateOperator, Object>>>andReturn()
                    // Special case, handle bean template
                    .when(e -> null == e, __ -> kv)
                    .when(JsonNode.class,
                            j -> Maps.immutableEntry(kv.getKey(),
                                    Tuples._2T(kv.getValue()._1(), convertJsonBean(j, object_mapper))))
                    .when(BeanTemplate.class,
                            e -> Maps.immutableEntry(kv.getKey(),
                                    Tuples._2T(kv.getValue()._1(), convertBeanTemplate(e, object_mapper))))
                    // Special case, handle list of bean templates
                    .when(Collection.class, l -> !l.isEmpty() && (l.iterator().next() instanceof JsonNode),
                            l -> Maps.immutableEntry(kv.getKey(),
                                    Tuples._2T(kv.getValue()._1(),
                                            l.stream().map(j -> convertJsonBean((JsonNode) j, object_mapper))
                                                    .collect(Collectors.toList()))))
                    .when(Collection.class, l -> !l.isEmpty() && (l.iterator().next() instanceof BeanTemplate),
                            l -> Maps.immutableEntry(kv.getKey(), Tuples._2T(kv.getValue()._1(), l.stream()
                                    .map(e -> convertBeanTemplate((BeanTemplate<Object>) e, object_mapper))
                                    .collect(Collectors.toList()))))
                    .otherwise(() -> kv))
            .collect(Collector.of(BasicDBObject::new, (acc, kv) -> {
                Patterns.match(kv.getValue()._2()).andAct()
                        // Delete operator, bunch of things have to happen for safety
                        .when(o -> ((UpdateOperator.unset == kv.getValue()._1()) && kv.getKey().isEmpty()
                                && (null == kv.getValue()._2())), o -> acc.put("$unset", null))
                        //Increment
                        .when(Number.class, n -> (UpdateOperator.increment == kv.getValue()._1()),
                                n -> nestedPut(acc, "$inc", kv.getKey(), n))
                        // Set
                        .when(o -> (UpdateOperator.set == kv.getValue()._1()),
                                o -> nestedPut(acc, "$set", kv.getKey(), o))
                        // Unset
                        .when(o -> (UpdateOperator.unset == kv.getValue()._1()),
                                o -> nestedPut(acc, "$unset", kv.getKey(), 1))
                        // Add items/item to list
                        .when(Collection.class, c -> (UpdateOperator.add == kv.getValue()._1()),
                                c -> nestedPut(acc, "$push", kv.getKey(), new BasicDBObject("$each", c)))
                        .when(o -> (UpdateOperator.add == kv.getValue()._1()),
                                o -> nestedPut(acc, "$push", kv.getKey(), o))
                        // Add item/items to set
                        .when(Collection.class, c -> (UpdateOperator.add_deduplicate == kv.getValue()._1()),
                                c -> nestedPut(acc, "$addToSet", kv.getKey(), new BasicDBObject("$each", c)))
                        .when(o -> (UpdateOperator.add_deduplicate == kv.getValue()._1()),
                                o -> nestedPut(acc, "$addToSet", kv.getKey(), o))
                        // Remove items from list by query
                        .when(QueryComponent.class, q -> (UpdateOperator.remove == kv.getValue()._1()),
                                q -> nestedPut(acc, "$pull", kv.getKey(), convertToMongoQuery(q)._1()))
                        // Remove items/item from list
                        .when(Collection.class, c -> (UpdateOperator.remove == kv.getValue()._1()),
                                c -> nestedPut(acc, "$pullAll", kv.getKey(), c))
                        .when(o -> (UpdateOperator.remove == kv.getValue()._1()),
                                o -> nestedPut(acc, "$pullAll", kv.getKey(), Arrays.asList(o)))
                        .otherwise(() -> {
                        }); // (do nothing)
            }, (a, b) -> {
                a.putAll(b.toMap());
                return a;
            }, Characteristics.UNORDERED));
}

From source file:org.briljantframework.data.Collectors.java

public static Collector<Vector, ?, DataFrame> toDataFrame(Supplier<DataFrame.Builder> supplier) {
    return Collector.of(supplier, (DataFrame.Builder acc, Vector record) -> {
        if (acc.columns() > 0 && record.size() != acc.columns()) {
            throw new IllegalStateException("All records must have the same size.");
        } else {/* w w  w  . j  a  v  a  2  s.c om*/
            acc.addRecord(Vectors.transferableBuilder(record));
        }
    }, (DataFrame.Builder left, DataFrame.Builder right) -> {
        if (left.columns() > 0 && left.rows() != right.columns()) {
            throw new IllegalStateException("Columns must all have the same length.");
        } else {
            for (Vector vector : right.build().getRecords()) {
                left.addRecord(Vectors.transferableBuilder(vector));
            }
            return left;
        }
    }, DataFrame.Builder::build);
}