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

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

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

Stream.sorted介绍

[英]Returns a stream consisting of the elements of this stream, sorted according to natural order. If the elements of this stream are not Comparable, a java.lang.ClassCastException may be thrown when the terminal operation is executed.

For ordered streams, the sort is stable. For unordered streams, no stability guarantees are made.

This is a stateful intermediate operation.
[中]返回由此流的元素组成的流,并根据自然顺序进行排序。如果此流的元素不可比较,则为java。执行终端操作时可能会引发lang.ClassCastException。
对于有序流,排序是稳定的。对于无序流,不保证稳定性。
这是一个stateful intermediate operation

代码示例

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

/**
 * Return all registered interceptors.
 */
protected List<Object> getInterceptors() {
  return this.registrations.stream()
      .sorted(INTERCEPTOR_ORDER_COMPARATOR)
      .map(InterceptorRegistration::getInterceptor)
      .collect(Collectors.toList());
}

代码示例来源:origin: GoogleContainerTools/jib

/**
  * Walks {@link #rootDir}.
  *
  * @return the walked files.
  * @throws IOException if walking the files fails.
  */
 public ImmutableList<Path> walk() throws IOException {
  try (Stream<Path> fileStream = Files.walk(rootDir)) {
   return fileStream.filter(pathFilter).sorted().collect(ImmutableList.toImmutableList());
  }
 }
}

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

public <T> void fireEvent(EventType type, Event event) {
  listenerMap.get(type).stream()
      .sorted(comparator)
      .forEach(listener -> listener.trigger(event));
}

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

public MessageProcessorsConfig withProcessors(final Set<String> availableProcessors) {
  final List<String> newOrder = new ArrayList<>();
  // Check if processor actually exists.
  processorOrder().stream()
      .filter(availableProcessors::contains)
      .forEach(newOrder::add);
  // Add availableProcessors which are not in the config yet to the end.
  availableProcessors.stream()
      .filter(processor -> !newOrder.contains(processor))
      .sorted(String.CASE_INSENSITIVE_ORDER)
      .forEach(newOrder::add);
  return toBuilder().processorOrder(newOrder).build();
}

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

private static List<Map.Entry<String, MetricStatsInt>> fiveBiggest(DistributedMetricStatsInt distributedMetricStatsInt, ToIntFunction<MetricStatsInt> biggerCriteria) {
 Comparator<Map.Entry<String, MetricStatsInt>> comparator = Comparator.comparingInt(a -> biggerCriteria.applyAsInt(a.getValue()));
 return distributedMetricStatsInt.getForLabels()
  .entrySet()
  .stream()
  .sorted(comparator.reversed())
  .limit(5)
  .collect(MoreCollectors.toList(5));
}

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

@Admin
@Description( "List the currently active config of Neo4j." )
@Procedure( name = "dbms.listConfig", mode = DBMS )
public Stream<ConfigResult> listConfig( @Name( value = "searchString", defaultValue = "" ) String searchString )
{
  Config config = graph.getDependencyResolver().resolveDependency( Config.class );
  String lowerCasedSearchString = searchString.toLowerCase();
  return config.getConfigValues().values().stream()
      .filter( c -> !c.internal() )
      .filter( c -> c.name().toLowerCase().contains( lowerCasedSearchString ) )
      .map( ConfigResult::new )
      .sorted( Comparator.comparing( c -> c.name ) );
}

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

@Description( "List all constraints in the database." )
@Procedure( name = "db.constraints", mode = READ )
public Stream<ConstraintResult> listConstraints()
{
  SchemaRead schemaRead = tx.schemaRead();
  TokenNameLookup tokens = new SilentTokenNameLookup( tx.tokenRead() );
  return asList( schemaRead.constraintsGetAll() )
      .stream()
      .map( constraint -> constraint.prettyPrint( tokens ) )
      .sorted()
      .map( ConstraintResult::new );
}

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

@Description( "List all procedures in the DBMS." )
@Procedure( name = "dbms.procedures", mode = DBMS )
public Stream<ProcedureResult> listProcedures()
{
  securityContext.assertCredentialsNotExpired();
  return graph.getDependencyResolver().resolveDependency( Procedures.class ).getAllProcedures().stream()
      .sorted( Comparator.comparing( a -> a.name().toString() ) )
      .map( ProcedureResult::new );
}

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

@SuppressFBWarnings("NP_NONNULL_RETURN_VIOLATION")
public synchronized @Nonnull Collection<HashedToken> getTokenListSortedByName() {
  return tokenList.stream()
      .sorted(SORT_BY_LOWERCASED_NAME)
      .collect(Collectors.toList());
}

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

public AuthenticationConfig withRealms(final Set<String> availableRealms) {
  final List<String> newOrder = new ArrayList<>();
  // Check if realm actually exists.
  realmOrder().stream()
      .filter(availableRealms::contains)
      .forEach(newOrder::add);
  // Add availableRealms which are not in the config yet to the end.
  availableRealms.stream()
      .filter(realm -> !newOrder.contains(realm))
      .sorted(String.CASE_INSENSITIVE_ORDER)
      .forEach(newOrder::add);
  return toBuilder().realmOrder(newOrder).build();
}

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

@GuardedBy("this")
  private String getAdditionalFailureInfo(long allocated, long delta)
  {
    Map<String, Long> queryAllocations = memoryPool.getTaggedMemoryAllocations().get(queryId);

    String additionalInfo = format("Allocated: %s, Delta: %s", succinctBytes(allocated), succinctBytes(delta));

    // It's possible that a query tries allocating more than the available memory
    // failing immediately before any allocation of that query is tagged
    if (queryAllocations == null) {
      return additionalInfo;
    }

    String topConsumers = queryAllocations.entrySet().stream()
        .sorted(comparingByValue(Comparator.reverseOrder()))
        .limit(3)
        .collect(toImmutableMap(Entry::getKey, e -> succinctBytes(e.getValue())))
        .toString();

    return format("%s, Top Consumers: %s", additionalInfo, topConsumers);
  }
}

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

private List<String> difference(Collection<String> expected, Collection<String> actual) {
 Set<String> actualSet = new HashSet<>(actual);
 return expected.stream()
  .filter(value -> !actualSet.contains(value))
  .sorted(String::compareTo)
  .collect(toList());
}

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

@Description( "List all user functions in the DBMS." )
@Procedure( name = "dbms.functions", mode = DBMS )
public Stream<FunctionResult> listFunctions()
{
  securityContext.assertCredentialsNotExpired();
  return graph.getDependencyResolver().resolveDependency( Procedures.class ).getAllFunctions().stream()
      .sorted( Comparator.comparing( a -> a.name().toString() ) )
      .map( FunctionResult::new );
}

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

public <T> void fireEvent(EventType type, Event event) {
  listenerMap.get(type).stream()
      .sorted(comparator)
      .forEach(listener -> listener.trigger(event));
}

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

@Nullable
private String getContentCodingKey(HttpServletRequest request) {
  String header = request.getHeader(HttpHeaders.ACCEPT_ENCODING);
  if (!StringUtils.hasText(header)) {
    return null;
  }
  return Arrays.stream(StringUtils.tokenizeToStringArray(header, ","))
      .map(token -> {
        int index = token.indexOf(';');
        return (index >= 0 ? token.substring(0, index) : token).trim().toLowerCase();
      })
      .filter(this.contentCodings::contains)
      .sorted()
      .collect(Collectors.joining(","));
}

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

@GuardedBy("this")
  private String getAdditionalFailureInfo(long allocated, long delta)
  {
    Map<String, Long> queryAllocations = memoryPool.getTaggedMemoryAllocations().get(queryId);

    String additionalInfo = format("Allocated: %s, Delta: %s", succinctBytes(allocated), succinctBytes(delta));

    // It's possible that a query tries allocating more than the available memory
    // failing immediately before any allocation of that query is tagged
    if (queryAllocations == null) {
      return additionalInfo;
    }

    String topConsumers = queryAllocations.entrySet().stream()
        .sorted(comparingByValue(Comparator.reverseOrder()))
        .limit(3)
        .collect(toImmutableMap(Entry::getKey, e -> succinctBytes(e.getValue())))
        .toString();

    return format("%s, Top Consumers: %s", additionalInfo, topConsumers);
  }
}

代码示例来源: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: org.springframework/spring-webmvc

/**
 * Return all registered interceptors.
 */
protected List<Object> getInterceptors() {
  return this.registrations.stream()
      .sorted(INTERCEPTOR_ORDER_COMPARATOR)
      .map(InterceptorRegistration::getInterceptor)
      .collect(Collectors.toList());
}

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

@Nullable
private String getContentCodingKey(ServerWebExchange exchange) {
  String header = exchange.getRequest().getHeaders().getFirst("Accept-Encoding");
  if (!StringUtils.hasText(header)) {
    return null;
  }
  return Arrays.stream(StringUtils.tokenizeToStringArray(header, ","))
      .map(token -> {
        int index = token.indexOf(';');
        return (index >= 0 ? token.substring(0, index) : token).trim().toLowerCase();
      })
      .filter(this.contentCodings::contains)
      .sorted()
      .collect(Collectors.joining(","));
}

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

public List<SearchResponseDecorator> searchResponseDecoratorsForStream(String streamId) {
  return this.decoratorService.findForStream(streamId)
    .stream()
    .sorted()
    .map(this::instantiateSearchResponseDecorator)
    .filter(Objects::nonNull)
    .collect(Collectors.toList());
}

相关文章