当前位置: 首页>>代码示例>>Java>>正文


Java Stream.reduce方法代码示例

本文整理汇总了Java中java.util.stream.Stream.reduce方法的典型用法代码示例。如果您正苦于以下问题:Java Stream.reduce方法的具体用法?Java Stream.reduce怎么用?Java Stream.reduce使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.util.stream.Stream的用法示例。


在下文中一共展示了Stream.reduce方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: map

import java.util.stream.Stream; //导入方法依赖的package包/类
public static <I, O> List<O> map(Stream<I> stream, Function<I, O> mapper) {
    return stream.reduce(new ArrayList<O>(), (acc, x) -> {
    	// We are copying data from acc to new list instance. It is very inefficient,
    	// but contract of Stream.reduce method requires that accumulator function does
    	// not mutate its arguments.
    	// Stream.collect method could be used to implement more efficient mutable reduction,
    	// but this exercise asks to use reduce method.
    	List<O> newAcc = new ArrayList<>(acc);
    	newAcc.add(mapper.apply(x));
        return newAcc;
    }, (List<O> left, List<O> right) -> {
    	// We are copying left to new list to avoid mutating it. 
    	List<O> newLeft = new ArrayList<>(left);
    	newLeft.addAll(right);
        return newLeft;
    });
}
 
开发者ID:jinyi233,项目名称:https-github.com-RichardWarburton-java-8-Lambdas-exercises,代码行数:18,代码来源:MapUsingReduce.java

示例2: filter

import java.util.stream.Stream; //导入方法依赖的package包/类
public static <I> List<I> filter(Stream<I> stream, Predicate<I> predicate) {
    List<I> initial = new ArrayList<>();
    return stream.reduce(initial,
                         (List<I> acc, I x) -> {
                            if (predicate.test(x)) {
                            	// We are copying data from acc to new list instance. It is very inefficient,
                            	// but contract of Stream.reduce method requires that accumulator function does
                            	// not mutate its arguments.
                            	// Stream.collect method could be used to implement more efficient mutable reduction,
                            	// but this exercise asks to use reduce method explicitly.
                            	List<I> newAcc = new ArrayList<>(acc);
                                newAcc.add(x);
                                return newAcc;
                            } else {
                            	return acc;
                            }
                         },
                         FilterUsingReduce::combineLists);
}
 
开发者ID:jinyi233,项目名称:https-github.com-RichardWarburton-java-8-Lambdas-exercises,代码行数:20,代码来源:FilterUsingReduce.java

示例3: executeFirstMatchConstraint

import java.util.stream.Stream; //导入方法依赖的package包/类
private List<? extends Element> executeFirstMatchConstraint(
        MemgraphCypherQueryContext ctx,
        MatchConstraint<?, ?> matchConstraint,
        ExpressionScope scope
) {
    try {
        List<String> labelNames = getLabelNamesFromMatchConstraint(matchConstraint);
        ListMultimap<String, CypherAstBase> propertiesMap = getPropertiesMapFromElementPatterns(ctx, matchConstraint.getPatterns());
        Iterable<? extends Element> elements;
        if (labelNames.size() == 0 && propertiesMap.size() == 0) {
            if (matchConstraint instanceof NodeMatchConstraint) {
                elements = ctx.getGraph().getVertices(ctx.getFetchHints(), ctx.getAuthorizations());
            } else if (matchConstraint instanceof RelationshipMatchConstraint) {
                elements = ctx.getGraph().getEdges(ctx.getFetchHints(), ctx.getAuthorizations());
            } else {
                throw new MemgraphCypherNotImplemented("unexpected constraint type: " + matchConstraint.getClass().getName());
            }
        } else {
            Query query = ctx.getGraph().query(ctx.getAuthorizations());

            if (labelNames.size() > 0) {
                Stream<String> labelNamesStream = labelNames.stream()
                        .map(ctx::normalizeLabelName);

                if (matchConstraint instanceof NodeMatchConstraint) {

                    query = labelNamesStream
                            .reduce(
                                    query,
                                    (q, labelName) -> q.has(ctx.getLabelPropertyName(), labelName),
                                    (q, q2) -> q
                            );
                } else if (matchConstraint instanceof RelationshipMatchConstraint) {
                    List<String> normalizedLabelNames = labelNamesStream.collect(Collectors.toList());
                    query = query.hasEdgeLabel(normalizedLabelNames);
                } else {
                    throw new MemgraphCypherNotImplemented("unexpected constraint type: " + matchConstraint.getClass().getName());
                }
            }

            for (Map.Entry<String, CypherAstBase> propertyMatch : propertiesMap.entries()) {
                Object value = ctx.getExpressionExecutor().executeExpression(ctx, propertyMatch.getValue(), scope);
                if (value instanceof CypherAstBase) {
                    throw new MemgraphException("unexpected value: " + value.getClass().getName() + ": " + value);
                }
                if (value instanceof List) {
                    query.has(propertyMatch.getKey(), Contains.IN, value);
                } else {
                    query.has(propertyMatch.getKey(), value);
                }
            }

            if (matchConstraint instanceof NodeMatchConstraint) {
                elements = query.vertices(ctx.getFetchHints());
            } else if (matchConstraint instanceof RelationshipMatchConstraint) {
                elements = query.edges(ctx.getFetchHints());
            } else {
                throw new MemgraphCypherNotImplemented("unexpected constraint type: " + matchConstraint.getClass().getName());
            }
        }

        return Lists.newArrayList(elements);
    } catch (MemgraphPropertyNotDefinedException e) {
        LOGGER.error(e.getMessage());
        return Lists.newArrayList();
    }
}
 
开发者ID:mware-solutions,项目名称:memory-graph,代码行数:68,代码来源:MatchClauseExecutor.java

示例4: addUp

import java.util.stream.Stream; //导入方法依赖的package包/类
public static int addUp(Stream<Integer> numbers) {
    return numbers.reduce(0, (acc, x) -> acc + x);
}
 
开发者ID:jinyi233,项目名称:https-github.com-RichardWarburton-java-8-Lambdas-exercises,代码行数:4,代码来源:Question1.java

示例5: operate

import java.util.stream.Stream; //导入方法依赖的package包/类
@Override
Object operate(Stream<?> stream) {
  return stream.reduce((a, b) -> b);
}
 
开发者ID:zugzug90,项目名称:guava-mock,代码行数:5,代码来源:StreamsBenchmark.java

示例6: flatten

import java.util.stream.Stream; //导入方法依赖的package包/类
public static <T> Stream<T> flatten(Stream<Stream<T>> streams){
	return streams.reduce(Stream.empty(), Stream::concat);
}
 
开发者ID:hotpads,项目名称:datarouter,代码行数:4,代码来源:StreamTool.java

示例7: reduce

import java.util.stream.Stream; //导入方法依赖的package包/类
static Optional<StackFrame> reduce(Stream<StackFrame> stream) {
    return stream.reduce((r,f) -> r.getClassName().compareTo(f.getClassName()) > 0 ? f : r);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:4,代码来源:WalkFunction.java

示例8: allInSequence

import java.util.stream.Stream; //导入方法依赖的package包/类
/**
 * Execute all the computations in the list in sequence. Return a completable future which will complete as follows:-
 * If any succeeded (marked by a completion value of true) complete with true, otherwise complete with false
 * @return completable future representing the combined result above
 */
public static CompletableFuture<Boolean> allInSequence(final Stream<Supplier<CompletableFuture<Boolean>>> futureSuppliers) {
    return futureSuppliers.reduce(completedFuture(Boolean.FALSE),
            (f, a) -> f.thenCompose(b1 -> a.get().thenCompose(b2 -> CompletableFuture.completedFuture(b1 || b2))),
            (bf1, bf2) -> bf1.thenCompose(b1 -> bf2.thenCompose(b2 -> CompletableFuture.completedFuture(b1 || b2))));
}
 
开发者ID:millross,项目名称:pac4j-async,代码行数:11,代码来源:FutureUtils.java

示例9: shortCircuitedFuture

import java.util.stream.Stream; //导入方法依赖的package包/类
public static CompletableFuture<Boolean> shortCircuitedFuture(final Stream<Supplier<CompletableFuture<Boolean>>> futureSuppliers,
                                                              final Boolean fallbackOn) {
    return futureSuppliers.reduce(completedFuture(!fallbackOn),
            (f, a) -> f.thenCompose(b -> (b != fallbackOn) ? a.get() : completedFuture(fallbackOn)),
            (bf1, bf2) -> bf1.thenCompose(b  -> (b != fallbackOn) ? bf2 : CompletableFuture.completedFuture(fallbackOn)));
}
 
开发者ID:millross,项目名称:pac4j-async,代码行数:7,代码来源:FutureUtils.java

示例10: compose

import java.util.stream.Stream; //导入方法依赖的package包/类
/**
 * Takes a Stream of functions (which take and return the same type) and composes
 * them into a single function, applying the provided functions in order
 */
static <T> Function<T, T> compose(Stream<Function<T, T>> functions) {
    return functions.reduce(identity(), Function::andThen);
}
 
开发者ID:unruly,项目名称:control,代码行数:8,代码来源:HigherOrderFunctions.java

示例11: fold

import java.util.stream.Stream; //导入方法依赖的package包/类
/**
 * "Multiplies" the given sequence of objects.
 * This is the canonical reduction operation on the free monoid, see e.g. 
 * <a href="https://en.wikipedia.org/wiki/Monoid#Monoids_in_computer_science">
 * monoids in computer science</a>.
 * @param ts the values to multiply.
 * @return the result of multiplying the stream of values.
 * @throws NullPointerException if the argument is {@code null} or any of
 * the contained objects is {@code null}.
 */
public T fold(Stream<T> ts) {
    requireNonNull(ts, "ts");
    return ts.reduce(monoid.unit(), monoid::multiply);
}
 
开发者ID:openmicroscopy,项目名称:omero-ms-queue,代码行数:15,代码来源:Monoids.java


注:本文中的java.util.stream.Stream.reduce方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。