java.util.stream.Stream类的使用及代码示例

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

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

Stream介绍

[英]A sequence of elements supporting sequential and parallel aggregate operations. The following example illustrates an aggregate operation using Stream and IntStream:

int sum = widgets.stream()

In this example, widgets is a Collection. We create a stream of Widget objects via Collection#stream, filter it to produce a stream containing only the red widgets, and then transform it into a stream of int values representing the weight of each red widget. Then this stream is summed to produce a total weight.

In addition to Stream, which is a stream of object references, there are primitive specializations for IntStream, LongStream, and DoubleStream, all of which are referred to as "streams" and conform to the characteristics and restrictions described here.

To perform a computation, stream operations are composed into a stream pipeline. A stream pipeline consists of a source (which might be an array, a collection, a generator function, an I/O channel, etc), zero or more intermediate operations (which transform a stream into another stream, such as Stream#filter(Predicate)), and a terminal operation (which produces a result or side-effect, such as Stream#count() or Stream#forEach(Consumer)). Streams are lazy; computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only as needed.

Collections and streams, while bearing some superficial similarities, have different goals. Collections are primarily concerned with the efficient management of, and access to, their elements. By contrast, streams do not provide a means to directly access or manipulate their elements, and are instead concerned with declaratively describing their source and the computational operations which will be performed in aggregate on that source. However, if the provided stream operations do not offer the desired functionality, the #iterator() and #spliterator() operations can be used to perform a controlled traversal.

A stream pipeline, like the "widgets" example above, can be viewed as a query on the stream source. Unless the source was explicitly designed for concurrent modification (such as a ConcurrentHashMap), unpredictable or erroneous behavior may result from modifying the stream source while it is being queried.

Most stream operations accept parameters that describe user-specified behavior, such as the lambda expression w -> w.getWeight() passed to mapToInt in the example above. To preserve correct behavior, these behavioral parameters:

  • must be non-interfering (they do not modify the stream source); and
  • in most cases must be stateless (their result should not depend on any state that might change during execution of the stream pipeline).

Such parameters are always instances of a functional interface such as java.util.function.Function, and are often lambda expressions or method references. Unless otherwise specified these parameters must be non-null.

A stream should be operated on (invoking an intermediate or terminal stream operation) only once. This rules out, for example, "forked" streams, where the same source feeds two or more pipelines, or multiple traversals of the same stream. A stream implementation may throw IllegalStateExceptionif it detects that the stream is being reused. However, since some stream operations may return their receiver rather than a new stream object, it may not be possible to detect reuse in all cases.

Streams have a #close() method and implement AutoCloseable, but nearly all stream instances do not actually need to be closed after use. Generally, only streams whose source is an IO channel (such as those returned by Files#lines(Path,Charset)) will require closing. Most streams are backed by collections, arrays, or generating functions, which require no special resource management. (If a stream does require closing, it can be declared as a resource in a try-with-resources statement.)

Stream pipelines may execute either sequentially or in parallel. This execution mode is a property of the stream. Streams are created with an initial choice of sequential or parallel execution. (For example, Collection#stream() creates a sequential stream, and Collection#parallelStream() creates a parallel one.) This choice of execution mode may be modified by the #sequential() or #parallel() methods, and may be queried with the #isParallel() method.
[中]支持顺序和并行聚合操作的元素序列。以下示例演示了使用Stream和IntStream的聚合操作:

int sum = widgets.stream()

在本例中,小部件是一个集合。我们通过Collection#stream创建一个Widget对象流,对其进行过滤以生成一个只包含红色Widget的流,然后将其转换为表示每个红色Widget权重的int值流。然后对该流求和以产生总重量。
除了Stream(对象引用流)之外,还有IntStream、LongStream和DoubleStream的基本专门化,所有这些都称为“streams”,并符合此处描述的特征和限制。
要执行计算,将流operations组合成流管道。流管道由源(可能是数组、集合、生成器函数、I/O通道等)、零个或多个中间操作(将流转换为另一个流,如流#过滤器(谓词)),以及终端操作(产生结果或副作用,如Stream#count()或Stream#forEach(Consumer))。溪流是懒惰的;仅当终端操作启动时才对源数据执行计算,并且仅在需要时使用源元素。
集合和流虽然表面上有一些相似之处,但目标不同。集合主要涉及对其元素的有效管理和访问。相反,流不提供直接访问或操作其元素的方法,而是以声明方式描述其源以及将在该源上聚合执行的计算操作。但是,如果提供的流操作没有提供所需的功能,则可以使用#iterator()和#spliterator()操作来执行受控遍历。
流管道,如上面的“小部件”示例,可以被视为流源上的查询。除非源是为并发修改而明确设计的(例如ConcurrentHashMap),否则在查询流源时修改流源可能会导致不可预测或错误的行为。
大多数流操作都接受描述用户指定行为的参数,例如上面示例中传递给mapToInt的lambda表达式w->w.getWeight()。要保留正确的行为,请使用以下行为参数
必须是non-interfering(它们不修改流源);和
在大多数情况下必须是stateless(它们的结果不应该依赖于流管道执行期间可能更改的任何状态)。
这些参数总是functional interface的实例,比如java。util。作用函数,并且通常是lambda表达式或方法引用。除非另有规定,否则这些参数必须为
非空

流只能操作一次(调用中间或终端流操作)。例如,这排除了“分叉”流,即同一个源向两个或多个管道提供数据,或对同一个流进行多次遍历。如果流实现检测到流正在被重用,则可能抛出IllegalStateException。然而,由于某些流操作可能返回其接收器而不是新的流对象,因此可能无法在所有情况下检测重用。
流有一个#close()方法并实现自动关闭,但几乎所有流实例在使用后实际上都不需要关闭。通常,只有源为IO通道的流(例如由文件#行(路径,字符集)返回的流)才需要关闭。大多数流都由集合、数组或生成函数支持,它们不需要特殊的资源管理。(如果流确实需要关闭,则可以在try with resources语句中将其声明为资源。)
流管道可以顺序执行,也可以在parallel中执行。此执行模式是流的属性。流是通过顺序或并行执行的初始选择创建的。(例如,Collection#stream()创建一个顺序流,Collection#parallelStream()创建一个并行流。)这种执行模式的选择可以通过#sequential()或#parallel()方法修改,也可以通过#isParallel()方法查询。

代码示例

canonical example by Tabnine

public List<Integer> findDivisors(int number) {
 return Stream.iterate(1, k -> ++k)
   .limit(number)
   .filter(k -> number % k == 0)
   .collect(Collectors.toList());
}

canonical example by Tabnine

public void printFibonacciSequence(int length) {
 System.out.println(
   Stream.iterate(new long[] {0, 1}, pair -> new long[] {pair[1], pair[0] + pair[1]})
     .limit(length)
     .map(pair -> Long.toString(pair[1]))
     .collect(Collectors.joining(", ")));
}

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

private List<SyncHandlerMethodArgumentResolver> initBinderResolvers(
    ArgumentResolverConfigurer customResolvers, ReactiveAdapterRegistry reactiveRegistry,
    ConfigurableApplicationContext context) {
  return initResolvers(customResolvers, reactiveRegistry, context, false, Collections.emptyList()).stream()
      .filter(resolver -> resolver instanceof SyncHandlerMethodArgumentResolver)
      .map(resolver -> (SyncHandlerMethodArgumentResolver) resolver)
      .collect(Collectors.toList());
}

代码示例来源: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: spring-projects/spring-framework

@Override
@Nullable
public CorsConfiguration getCorsConfiguration(ServerWebExchange exchange) {
  PathContainer lookupPath = exchange.getRequest().getPath().pathWithinApplication();
  return this.corsConfigurations.entrySet().stream()
      .filter(entry -> entry.getKey().matches(lookupPath))
      .map(Map.Entry::getValue)
      .findFirst()
      .orElse(null);
}

代码示例来源: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: spring-projects/spring-framework

@Nullable
private static MediaType initDefaultMediaType(List<MediaType> mediaTypes) {
  return mediaTypes.stream().filter(MediaType::isConcrete).findFirst().orElse(null);
}

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

public List<Symbol> getOriginalNonDistinctAggregateArgs()
{
  return aggregations.values().stream()
      .filter(aggregation -> !aggregation.getMask().isPresent())
      .map(Aggregation::getCall)
      .flatMap(function -> function.getArguments().stream())
      .distinct()
      .map(Symbol::from)
      .collect(Collectors.toList());
}

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

private static List<PathPattern> parse(String[] paths, PathPatternParser parser) {
    return Arrays
        .stream(paths)
        .map(path -> {
          if (StringUtils.hasText(path) && !path.startsWith("/")) {
            path = "/" + path;
          }
          return parser.parse(path);
        })
        .collect(Collectors.toList());
  }
}

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

@Override
public Map<String, PartitionStatistics> getPartitionStatistics(String databaseName, String tableName, Set<String> partitionNames)
{
  List<HivePartitionName> partitions = partitionNames.stream()
      .map(partitionName -> HivePartitionName.hivePartitionName(databaseName, tableName, partitionName))
      .collect(toImmutableList());
  Map<HivePartitionName, PartitionStatistics> statistics = getAll(partitionStatisticsCache, partitions);
  return statistics.entrySet()
      .stream()
      .collect(toImmutableMap(entry -> entry.getKey().getPartitionName().get(), Entry::getValue));
}

代码示例来源:origin: apache/incubator-dubbo

@Override
public synchronized void notify(List<URL> urls) {
  List<URL> categoryUrls = urls.stream()
      .filter(this::isValidCategory)
      .filter(this::isNotCompatibleFor26x)
      .collect(Collectors.toList());
  /**
   * TODO Try to refactor the processing of these three type of urls using Collectors.groupBy()?
   */
  this.configurators = Configurator.toConfigurators(classifyUrls(categoryUrls, UrlUtils::isConfigurator))
      .orElse(configurators);
  toRouters(classifyUrls(categoryUrls, UrlUtils::isRoute)).ifPresent(this::addRouters);
  // providers
  refreshOverrideAndInvoker(classifyUrls(categoryUrls, UrlUtils::isProvider));
}

代码示例来源:origin: google/guava

public void testToOptionalNull() {
 Stream<Object> stream = Stream.of((Object) null);
 try {
  stream.collect(MoreCollectors.toOptional());
  fail("Expected NullPointerException");
 } catch (NullPointerException expected) {
 }
}

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

public static RowType anonymous(List<Type> types)
{
  List<Field> fields = types.stream()
      .map(type -> new Field(Optional.empty(), type))
      .collect(Collectors.toList());
  return new RowType(makeSignature(fields), fields);
}

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

private synchronized Collection<HivePrivilegeInfo> getTablePrivileges(
    Path permissionsDirectory,
    String principalName,
    PrincipalType principalType)
{
  Path permissionFilePath = getPermissionsPath(permissionsDirectory, principalName, principalType);
  return readFile("permissions", permissionFilePath, permissionsCodec).orElse(ImmutableList.of()).stream()
      .map(PermissionMetadata::toHivePrivilegeInfo)
      .collect(toList());
}

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

private static PlanFragment createExchangePlanFragment(String name, PlanFragment... fragments)
{
  PlanNode planNode = new RemoteSourceNode(
      new PlanNodeId(name + "_id"),
      Stream.of(fragments)
          .map(PlanFragment::getId)
          .collect(toImmutableList()),
      fragments[0].getPartitioningScheme().getOutputLayout(),
      Optional.empty(),
      REPARTITION);
  return createFragment(planNode);
}

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

@VisibleForTesting
public Supplier<PageProcessor> createPageProcessor(Page filterTuple, OptionalInt initialBatchSize)
{
  TuplePageFilter filter = new TuplePageFilter(filterTuple, filterTypes, outputFilterChannels);
  return () -> new PageProcessor(
      Optional.of(filter),
      outputProjections.stream()
          .map(Supplier::get)
          .collect(toImmutableList()), initialBatchSize);
}

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

private Set<NullableValue> filterValues(Set<NullableValue> nullableValues, TpchColumn<?> column, Constraint<ColumnHandle> constraint)
{
  return nullableValues.stream()
      .filter(convertToPredicate(constraint.getSummary(), toColumnHandle(column)))
      .filter(value -> !constraint.predicate().isPresent() || constraint.predicate().get().test(ImmutableMap.of(toColumnHandle(column), value)))
      .collect(toSet());
}

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

private List<MediaType> getMediaTypesFor(ResolvableType elementType) {
  return getMessageWriters().stream()
      .filter(converter -> converter.canWrite(elementType, null))
      .flatMap(converter -> converter.getWritableMediaTypes().stream())
      .collect(Collectors.toList());
}

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

public List<SchemaTableName> listTables(Optional<String> schemaName)
{
  return tableDescriptions.getAllSchemaTableNames()
      .stream()
      .filter(schemaTableName -> !schemaName.isPresent() || schemaTableName.getSchemaName().equals(schemaName.get()))
      .collect(toImmutableList());
}

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

private static TypeSignature makeSignature(List<Field> fields)
{
  int size = fields.size();
  if (size == 0) {
    throw new IllegalArgumentException("Row type must have at least 1 field");
  }
  List<TypeSignatureParameter> parameters = fields.stream()
      .map(field -> TypeSignatureParameter.of(new NamedTypeSignature(field.getName().map(name -> new RowFieldName(name, false)), field.getType().getTypeSignature())))
      .collect(Collectors.toList());
  return new TypeSignature(ROW, parameters);
}

相关文章