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

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

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

Stream.forEach介绍

[英]Performs an action for each element of this stream.

This is a terminal operation.

The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism. For any given element, the action may be performed at whatever time and in whatever thread the library chooses. If the action accesses shared state, it is responsible for providing the required synchronization.
[中]为此流的每个元素执行操作。
这是一个terminal operation
此操作的行为显然是不确定的。对于并行流管道,此操作保证尊重流的相遇顺序,因为这样做会牺牲并行性的好处。对于任何给定的元素,可以在库选择的任何时间和线程中执行该操作。如果操作访问共享状态,则它负责提供所需的同步。

代码示例

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

/**
 * Match handlers declared under a base package, e.g. "org.example".
 * @param packages one or more base package classes
 */
public Builder basePackage(String... packages) {
  Arrays.stream(packages).filter(StringUtils::hasText).forEach(this::addBasePackage);
  return this;
}

代码示例来源:origin: eclipse-vertx/vert.x

@Override
public Collection<CommandFactory<?>> lookup() {
 List<CommandFactory<?>> list = new ArrayList<>();
 commands.stream().forEach(list::add);
 return list;
}

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

/**
 * Configure path prefixes to apply to controller methods.
 * <p>Prefixes are used to enrich the mappings of every {@code @RequestMapping}
 * method whose controller type is matched by a corresponding
 * {@code Predicate} in the map. The prefix for the first matching predicate
 * is used, assuming the input map has predictable order.
 * <p>Consider using {@link org.springframework.web.method.HandlerTypePredicate
 * HandlerTypePredicate} to group controllers.
 * @param prefixes a map with path prefixes as key
 * @since 5.1
 * @see org.springframework.web.method.HandlerTypePredicate
 */
public void setPathPrefixes(Map<String, Predicate<Class<?>>> prefixes) {
  this.pathPrefixes.clear();
  prefixes.entrySet().stream()
      .filter(entry -> StringUtils.hasText(entry.getKey()))
      .forEach(entry -> this.pathPrefixes.put(entry.getKey(), entry.getValue()));
}

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

/**
 * Provide the TaskScheduler to use for SockJS endpoints for which a task
 * scheduler has not been explicitly registered. This method must be called
 * prior to {@link #getHandlerMapping()}.
 */
protected void setTaskScheduler(TaskScheduler scheduler) {
  this.registrations.stream()
      .map(ServletWebSocketHandlerRegistration::getSockJsServiceRegistration)
      .filter(Objects::nonNull)
      .filter(r -> r.getTaskScheduler() == null)
      .forEach(registration -> registration.setTaskScheduler(scheduler));
}

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

/** 8. Using Java 8 Stream Api parallel **/
@Benchmark
public long test8_UsingJava8StreamApiParallel() throws IOException {
  final long[] i = {0};
  map.entrySet().stream().parallel().forEach(e -> i[0] += e.getKey() + e.getValue());
  return i[0];
}

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

private static List<Type> toTypes(List<Type> groupByTypes, List<Aggregator> aggregates)
{
  ImmutableList.Builder<Type> builder = ImmutableList.builder();
  builder.addAll(groupByTypes);
  aggregates.stream()
      .map(Aggregator::getType)
      .forEach(builder::add);
  return builder.build();
}

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

private static void validatePropertySet(SetRequest request, @Nullable PropertyDefinition definition) {
 checkRequest(definition != null, "Setting '%s' is undefined", request.getKey());
 checkRequest(PropertyType.PROPERTY_SET.equals(definition.type()), "Parameter '%s' is used for setting of property set type only", PARAM_FIELD_VALUES);
 Set<String> fieldKeys = definition.fields().stream().map(PropertyFieldDefinition::key).collect(Collectors.toSet());
 ListMultimap<String, String> valuesByFieldKeys = ArrayListMultimap.create(fieldKeys.size(), request.getFieldValues().size() * fieldKeys.size());
 request.getFieldValues().stream()
  .map(oneFieldValues -> readOneFieldValues(oneFieldValues, request.getKey()))
  .peek(map -> checkRequest(map.values().stream().anyMatch(StringUtils::isNotBlank), MSG_NO_EMPTY_VALUE))
  .flatMap(map -> map.entrySet().stream())
  .peek(entry -> valuesByFieldKeys.put(entry.getKey(), entry.getValue()))
  .forEach(entry -> checkRequest(fieldKeys.contains(entry.getKey()), "Unknown field key '%s' for setting '%s'", entry.getKey(), request.getKey()));
 checkFieldType(request, definition, valuesByFieldKeys);
}

代码示例来源:origin: jenkinsci/jenkins

private void parseFileIntoList(List<String> lines, Set<String> whitelist, Set<String> blacklist){
  lines.stream()
      .filter(line -> !line.matches("#.*|\\s*"))
      .forEach(line -> {
        if (line.startsWith("!")) {
          String withoutExclamation = line.substring(1);
          if (!withoutExclamation.isEmpty()) {
            blacklist.add(withoutExclamation);
          }
        } else {
          whitelist.add(line);
        }
      });
}

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

private List<Symbol> getPushedDownGroupingSet(AggregationNode aggregation, Set<Symbol> availableSymbols, Set<Symbol> requiredJoinSymbols)
{
  List<Symbol> groupingSet = aggregation.getGroupingKeys();
  // keep symbols that are directly from the join's child (availableSymbols)
  List<Symbol> pushedDownGroupingSet = groupingSet.stream()
      .filter(availableSymbols::contains)
      .collect(Collectors.toList());
  // add missing required join symbols to grouping set
  Set<Symbol> existingSymbols = new HashSet<>(pushedDownGroupingSet);
  requiredJoinSymbols.stream()
      .filter(existingSymbols::add)
      .forEach(pushedDownGroupingSet::add);
  return pushedDownGroupingSet;
}

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

private static <K,V> void copy(MultiValueMap<K,V> src, MultiValueMap<K,V> dst) {
    if (!src.isEmpty()) {
      src.entrySet().stream()
          .filter(entry -> !dst.containsKey(entry.getKey()))
          .forEach(entry -> dst.put(entry.getKey(), entry.getValue()));
    }
  }
}

代码示例来源:origin: Graylog2/graylog2-server

@Override
public void upgrade() {
  this.indexSetService.findAll()
    .stream()
    .map(mongoIndexSetFactory::create)
    .flatMap(indexSet -> getReopenedIndices(indexSet).stream())
    .map(indexName -> { LOG.debug("Marking index {} to be reopened using alias.", indexName); return indexName; })
    .forEach(indices::markIndexReopened);
}

代码示例来源:origin: lets-blade/blade

public String parsePath(String path) {
  if (StringKit.isBlank(path)) return path;
  String[] pathModule = path.split("/");
  Arrays.stream(pathModule)
      .filter(row -> !row.isEmpty())
      .map(this::rowToPath)
      .forEach(this::join);
  pathBuilder.deleteCharAt(pathBuilder.length() - 1);
  return build(true);
}

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

@Override
protected void applyCookies() {
  getCookies().values().stream().flatMap(Collection::stream)
      .map(cookie -> new DefaultCookie(cookie.getName(), cookie.getValue()))
      .forEach(this.request::addCookie);
}

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

/**
 * Create a new {@link MockMultipartHttpServletRequest} based on the
 * supplied {@code ServletContext} and the {@code MockMultipartFiles}
 * added to this builder.
 */
@Override
protected final MockHttpServletRequest createServletRequest(ServletContext servletContext) {
  MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest(servletContext);
  this.files.stream().forEach(request::addFile);
  this.parts.values().stream().flatMap(Collection::stream).forEach(request::addPart);
  if (!this.parts.isEmpty()) {
    new StandardMultipartHttpServletRequest(request)
        .getMultiFileMap().values().stream().flatMap(Collection::stream)
        .forEach(request::addFile);
  }
  return request;
}

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

public void setCookies(@Nullable Cookie... cookies) {
  this.cookies = (ObjectUtils.isEmpty(cookies) ? null : cookies);
  this.headers.remove(HttpHeaders.COOKIE);
  if (this.cookies != null) {
    Arrays.stream(this.cookies)
        .map(c -> c.getName() + '=' + (c.getValue() == null ? "" : c.getValue()))
        .forEach(value -> doAddHeaderValue(HttpHeaders.COOKIE, value, false));
  }
}

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

@Nullable
private Collection<CacheOperation> parseCacheAnnotations(
    DefaultCacheConfig cachingConfig, AnnotatedElement ae, boolean localOnly) {
  Collection<? extends Annotation> anns = (localOnly ?
      AnnotatedElementUtils.getAllMergedAnnotations(ae, CACHE_OPERATION_ANNOTATIONS) :
      AnnotatedElementUtils.findAllMergedAnnotations(ae, CACHE_OPERATION_ANNOTATIONS));
  if (anns.isEmpty()) {
    return null;
  }
  final Collection<CacheOperation> ops = new ArrayList<>(1);
  anns.stream().filter(ann -> ann instanceof Cacheable).forEach(
      ann -> ops.add(parseCacheableAnnotation(ae, cachingConfig, (Cacheable) ann)));
  anns.stream().filter(ann -> ann instanceof CacheEvict).forEach(
      ann -> ops.add(parseEvictAnnotation(ae, cachingConfig, (CacheEvict) ann)));
  anns.stream().filter(ann -> ann instanceof CachePut).forEach(
      ann -> ops.add(parsePutAnnotation(ae, cachingConfig, (CachePut) ann)));
  anns.stream().filter(ann -> ann instanceof Caching).forEach(
      ann -> parseCachingAnnotation(ae, cachingConfig, (Caching) ann, ops));
  return ops;
}

代码示例来源:origin: stanfordnlp/CoreNLP

public SortedMap<String, Double> getWeightVector() {
 SortedMap<String, Double> m = new TreeMap<>((f1, f2) -> {
  double weightDifference = Math.abs(weights.getCount(f2)) - Math.abs(weights.getCount(f1));
  return weightDifference == 0 ? f1.compareTo(f2) : (int) Math.signum(weightDifference);
 });
 weights.entrySet().stream().forEach(e -> m.put(e.getKey(), e.getValue()));
 return m;
}

代码示例来源:origin: ctripcorp/apollo

@Override
public List<UserInfo> findByUserIds(List<String> userIds) {
 if (CollectionUtils.isEmpty(userIds)) {
  return null;
 } else {
  ContainerCriteria criteria = query().where(loginIdAttrName).is(userIds.get(0));
  userIds.stream().skip(1).forEach(userId -> criteria.or(loginIdAttrName).is(userId));
  return ldapTemplate.search(ldapQueryCriteria().and(criteria), ldapUserInfoMapper);
 }
}

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

public void setEnableAllChecksAsWarnings(boolean enableAllChecksAsWarnings) {
 // Checks manually disabled before this flag are reset to warning-level
 severityMap.entrySet().stream()
   .filter(e -> e.getValue() == Severity.OFF)
   .forEach(e -> e.setValue(Severity.WARN));
 this.enableAllChecksAsWarnings = enableAllChecksAsWarnings;
}

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

public static <T> void registerQuerySuppiler(Class<T> type, Function<T, Query<T, QueryParamEntity>> querySupplier) {
  validatorCache.computeIfAbsent(type, instrance::createValidator)
      .values()
      .stream()
      .filter(DefaultValidator.class::isInstance)
      .map(DefaultValidator.class::cast)
      .forEach(validator -> validator.querySupplier = querySupplier);
}

相关文章