java.util.stream.Stream.reduce()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(8.5k)|赞(0)|评价(0)|浏览(312)

本文整理了Java中java.util.stream.Stream.reduce()方法的一些代码示例,展示了Stream.reduce()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Stream.reduce()方法的具体详情如下:
包路径:java.util.stream.Stream
类名称:Stream
方法名:reduce

Stream.reduce介绍

[英]Performs a reduction on the elements of this stream, using the provided identity, accumulation and combining functions. This is equivalent to:

U result = identity;

but is not constrained to execute sequentially.

The identity value must be an identity for the combiner function. This means that for all u, combiner(identity, u)is equal to u. Additionally, the combiner function must be compatible with the accumulator function; for all u and t, the following must hold:

combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u, t)

This is a terminal operation.
[中]使用提供的标识、累加和组合函数对此流的元素执行{$0$}。这相当于:

U result = identity;

但不受顺序执行的约束。
标识值必须是组合器函数的标识。这意味着对于所有u,组合器(标识,u)等于u。此外,组合器功能必须与累加器功能兼容;对于所有u和t,必须满足以下条件:

combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u, t)

这是一个terminal operation

代码示例

代码示例来源:origin: spring-projects/spring-framework

@Override
public RouterFunction<ServerResponse> build() {
  RouterFunction<ServerResponse> result = this.routerFunctions.stream()
      .reduce(RouterFunction::and)
      .orElseThrow(IllegalStateException::new);
  if (this.filterFunctions.isEmpty()) {
    return result;
  }
  else {
    HandlerFilterFunction<ServerResponse, ServerResponse> filter =
        this.filterFunctions.stream()
            .reduce(HandlerFilterFunction::andThen)
            .orElseThrow(IllegalStateException::new);
    return result.filter(filter);
  }
}

代码示例来源:origin: apache/pulsar

@Override
  public Integer apply(Collection<Integer> integers) {
    return integers.stream().reduce(0, (x, y) -> x + y);
  }
}

代码示例来源:origin: hs-web/hsweb-framework

@Override
public int updateByPk(List<E> data) {
  return data.stream()
      .map(this::updateByPk)
      .reduce(Math::addExact)
      .orElse(0);
}

代码示例来源:origin: SonarSource/sonarqube

@Override
public Health checkNode() {
 return nodeHealthChecks.stream()
  .map(NodeHealthCheck::check)
  .reduce(Health.GREEN, HealthReducer.INSTANCE);
}

代码示例来源:origin: wildfly/wildfly

public int size() {
  lock.lock();
  try {
    long num=msgs.values().stream().flatMap(Collection::stream).map(Message::size).reduce(0L, (a, b) -> a + b);
    return (int)num;
  }
  finally {
    lock.unlock();
  }
}

代码示例来源:origin: Vedenin/useful-java-links

Integer sum = collection.stream().reduce((s1, s2) -> s1 + s2).orElse(0); // using stream Api
Integer sumOld = 0; // using Java 7
for(Integer i: collection) {
Integer max1 = collection.stream().reduce((s1, s2) -> s1 > s2 ? s1 : s2).orElse(0); // using stream Api
Integer max2 = collection.stream().reduce(Integer::max).orElse(0); // using stream Api using Integer::max
Integer min = collection.stream().reduce((s1, s2) -> s1 < s2 ? s1 : s2).orElse(0);  // using stream Api
Integer last = collection.stream().reduce((s1, s2) -> s2).orElse(0); // using stream Api
Integer sumMore2 = collection.stream().filter(o -> o > 2).reduce((s1, s2) -> s1 + s2).orElse(0);     // using stream Api
Integer sumMore2Old = 0; // using Java 7
for(Integer i: collection) {
Integer sumOdd = collection.stream().filter(o -> o % 2 != 0).reduce((s1, s2) -> s1 + s2).orElse(0); // using stream Api
Integer sumOddOld = 0; // using Java 7
for(Integer i: collection) {
int oldMan = peoples.stream().filter((p) -> p.getSex() == Sex.MAN).map(People::getAge).reduce((s1, s2) -> s1 > s2 ? s1 : s2).get();
System.out.println("oldMan = " + oldMan); // print  69

代码示例来源:origin: google/error-prone

private static Optional<Nullness> fromAnnotationStream(Stream<String> annotations) {
 return annotations
   .filter(ANNOTATION_RELEVANT_TO_NULLNESS)
   .map(annot -> NULLABLE_ANNOTATION.test(annot) ? NULLABLE : NONNULL)
   .reduce(Nullness::greatestLowerBound);
}

代码示例来源:origin: hs-web/hsweb-framework

public Map<Class<Entity>, MapperEntityFactory.Mapper> createMappers() {
  if (mappings == null || mappings.isEmpty()) {
    return new java.util.HashMap<>();
  }
  return mappings.stream()
      .map(Mapping::create)
      .reduce(MapUtils::merge)
      .orElseGet(HashMap::new);
}

代码示例来源:origin: prestodb/presto

private TupleDomain<ColumnHandle> toTupleDomain(Map<TpchColumnHandle, Set<NullableValue>> predicate)
{
  return TupleDomain.withColumnDomains(predicate.entrySet().stream()
      .collect(Collectors.toMap(Map.Entry::getKey, entry -> {
        Type type = entry.getKey().getType();
        return entry.getValue().stream()
            .map(nullableValue -> Domain.singleValue(type, nullableValue.getValue()))
            .reduce((Domain::union))
            .orElse(Domain.none(type));
      })));
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Initialized the router functions by detecting them in the application context.
 */
protected void initRouterFunctions() {
  List<RouterFunction<?>> routerFunctions = routerFunctions();
  this.routerFunction = routerFunctions.stream().reduce(RouterFunction::andOther).orElse(null);
  logRouterFunctions(routerFunctions);
}

代码示例来源:origin: vert-x3/vertx-examples

private Predicate<Transaction> constructFilterPredicate(List<String> from, List<String> to, List<String> message) {
 List<Predicate<Transaction>> predicates = new ArrayList<>();
 if (from != null) {
  predicates.add(transaction -> from.contains(transaction.getFrom()));
 }
 if (to != null) {
  predicates.add(transaction -> to.contains(transaction.getTo()));
 }
 if (message != null) {
  predicates.add(transaction -> message.stream().filter(o -> ((String)o).contains(transaction.getMessage())).count() > 0);
 }
 // Elegant predicates combination
 return predicates.stream().reduce(transaction -> true, Predicate::and);
}

代码示例来源:origin: neo4j/neo4j

@Override
public IndexSample sampleIndex()
{
  return indexSamplers.parallelStream()
      .map( this::sampleIndex )
      .reduce( this::combine )
      .get();
}

代码示例来源:origin: SonarSource/sonarqube

public static Facet of(String name) {
  return stream(values())
   .filter(f -> f.getName().equals(name))
   .reduce((a, b) -> {
    throw new IllegalStateException("Multiple facets with same name: " + a + ", " + b);
   })
   .orElseThrow(() -> new IllegalArgumentException(String.format("Facet name '%s' hasn't been found", name)));
 }
}

代码示例来源:origin: speedment/speedment

private Stream<Film> serveFilmsWithfunctionalFold(String rating, int page) {
  System.out.format("serveFilmsWithfunctionalFold(String rating=%s, int page=%d) %n", rating, page);
  return Stream.<UnaryOperator<Stream<Film>>>of(
    (s) -> rating == null ? s : s.filter(Film.RATING.equal(rating)),
    s -> s.sorted(Film.LENGTH),
    s -> s.skip(page * PAGE_SIZE),
    s -> s.limit(PAGE_SIZE)
  ).reduce(
    films.stream(),
    (s, o) -> o.apply(s),
    (a, b) -> a
  );
}

代码示例来源:origin: apache/flink

private Optional<Event> verifyWindowContiguity(List<Event> newValues, Collector<String> out) {
    return newValues.stream()
      .sorted(Comparator.comparingLong(Event::getSequenceNumber))
      .reduce((event, event2) -> {
        if (event2.getSequenceNumber() - 1 != event.getSequenceNumber()) {
          out.collect("Alert: events in window out ouf order!");
        }

        return event2;
      });
  }
}

代码示例来源:origin: hs-web/hsweb-framework

protected AccessTokenModel entityToModel(OAuth2AccessToken token) {
  AccessTokenModel model = new AccessTokenModel();
  model.setAccess_token(token.getAccessToken());
  model.setRefresh_token(token.getRefreshToken());
  model.setExpires_in(token.getExpiresIn());
  if (token.getScope() != null) {
    model.setScope(token.getScope().stream().reduce((t1, t2) -> t1.concat(",").concat(t2)).orElse(""));
  } else {
    model.setScope("public");
  }
  model.setToken_type("bearer");
  return model;
}

代码示例来源:origin: neo4j/neo4j

@Override
public Boolean visitDeclared( DeclaredType declaredType, Void ignored )
{
  return allowedTypesValidator.test( declaredType ) &&
      declaredType.getTypeArguments().stream().map( this::visit ).reduce( ( a, b ) -> a && b ).orElse( Boolean.TRUE );
}

代码示例来源:origin: shekhargulati/java8-the-missing-tutorial

public String joinAllTaskTitles(List<Task> tasks) {
  return tasks.stream().
      map(Task::getTitle).
      reduce((first, second) -> first + " *** " + second).
      get();
}

代码示例来源:origin: neo4j/neo4j

public String description( String text )
{
  String wrappedText = wrapText( text, LINE_LENGTH );
  if ( namedArgs.isEmpty() )
  {
    return wrappedText;
  }
  wrappedText = String.join( NEWLINE + NEWLINE, wrappedText, "options:" );
  //noinspection OptionalGetWithoutIsPresent handled by if-statement above
  final int alignLength = namedArgs.values().stream()
      .map( a -> a.optionsListing().length() )
      .reduce( 0, Integer::max );
  return String.join( NEWLINE, wrappedText,
      namedArgs.values().stream()
          .map( c -> formatArgumentDescription( alignLength, c ) )
          .collect( Collectors.joining( NEWLINE ) ) );
}

代码示例来源:origin: SonarSource/sonarqube

@Override
public Health check(Set<NodeHealth> nodeHealths) {
 Set<NodeHealth> appNodes = nodeHealths.stream()
  .filter(s -> s.getDetails().getType() == NodeDetails.Type.APPLICATION)
  .collect(toSet());
 return Arrays.stream(AppNodeClusterHealthSubChecks.values())
  .map(s -> s.check(appNodes))
  .reduce(Health.GREEN, HealthReducer.INSTANCE);
}

相关文章