Stream.sorted
Code IndexAdd Codota to your IDE (free)

Best code snippets using java.util.stream.Stream.sorted(Showing top 20 results out of 4,527)

Refine search

  • Collectors.toList
  • Stream.collect
  • Stream.map
  • List.stream
  • Stream.filter
  • Set.stream
  • Common ways to obtain Stream
private void myMethod () {
Stream s =
  • Stream.empty()
  • List list;list.stream()
  • AI code suggestions by Codota
}
origin: prestodb/presto

  @Override
  public Expression rewriteLogicalBinaryExpression(LogicalBinaryExpression node, Void context, ExpressionTreeRewriter<Void> treeRewriter)
  {
    List<Expression> predicates = extractPredicates(node.getType(), node).stream()
        .map(p -> treeRewriter.rewrite(p, context))
        .sorted(Comparator.comparing(Expression::toString))
        .collect(toList());
    return binaryExpression(node.getType(), predicates);
  }
}
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());
}
origin: apache/flink

  default List<MessageHeaders> getSpecs() {
    Comparator<String> comparator = new RestServerEndpoint.RestHandlerUrlComparator.CaseInsensitiveOrderComparator();
    return initializeHandlers(CompletableFuture.completedFuture(null)).stream()
      .map(tuple -> tuple.f0)
      .filter(spec -> spec instanceof MessageHeaders)
      .map(spec -> (MessageHeaders) spec)
      .sorted((spec1, spec2) -> comparator.compare(spec1.getTargetRestEndpointURL(), spec2.getTargetRestEndpointURL()))
      .collect(Collectors.toList());
  }
}
origin: prestodb/presto

public static Expression toPredicate(TupleDomain<Symbol> tupleDomain)
{
  if (tupleDomain.isNone()) {
    return FALSE_LITERAL;
  }
  Map<Symbol, Domain> domains = tupleDomain.getDomains().get();
  return domains.entrySet().stream()
      .sorted(comparing(entry -> entry.getKey().getName()))
      .map(entry -> toPredicate(entry.getValue(), entry.getKey().toSymbolReference()))
      .collect(collectingAndThen(toImmutableList(), ExpressionUtils::combineConjuncts));
}
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: Graylog2/graylog2-server

private void loadExtractors(final String inputId) {
  LOG.debug("Re-loading extractors for input <{}>", inputId);
  try {
    final Input input = inputService.find(inputId);
    final List<Extractor> sortedExtractors = inputService.getExtractors(input).stream()
        .sorted(Comparator.comparingLong(Extractor::getOrder))
        .collect(Collectors.toList());
    extractors.put(inputId, ImmutableList.copyOf(sortedExtractors));
  } catch (NotFoundException e) {
    LOG.warn("Unable to load input <{}>: {}", inputId, e.getMessage());
  }
}
origin: prestodb/presto

private List<ColumnInfo> getColumnInfoFromOrcUserMetadata(OrcFileMetadata orcFileMetadata)
{
  return orcFileMetadata.getColumnTypes().entrySet()
      .stream()
      .sorted(Map.Entry.comparingByKey())
      .map(entry -> new ColumnInfo(entry.getKey(), typeManager.getType(entry.getValue())))
      .collect(toList());
}
origin: neo4j/neo4j

private List<File> listFolders( File rootFolder )
{
  File[] files = fileSystem.listFiles( rootFolder );
  return files == null ? Collections.emptyList()
             : Stream.of( files )
              .filter( fileSystem::isDirectory )
              .sorted( FILE_COMPARATOR )
              .collect( toList() );
}
origin: google/error-prone

 private static String getClassFixMessage(Collection<Name> methodNames) {
  String methods =
    methodNames
      .stream()
      .map(methodName -> String.format("\"%s\"", methodName.toString()))
      .sorted()
      .collect(Collectors.joining(", "));
  return String.format("Overloaded methods (%s) of this class are not grouped together", methods);
 }
}
origin: prestodb/presto

public static Set<String> reservedIdentifiers()
{
  return possibleIdentifiers().stream()
      .filter(ReservedIdentifiers::reserved)
      .sorted()
      .collect(toImmutableSet());
}
origin: neo4j/neo4j

private ProcedureException javaToNeoMappingError( Type cls )
{
  List<String> types = Iterables.asList( javaToNeo.keySet() )
      .stream()
      .map( Type::getTypeName )
      .sorted( String::compareTo )
      .collect( Collectors.toList() );
  return new ProcedureException( Status.Statement.TypeError,
      "Don't know how to map `%s` to the Neo4j Type System.%n" +
          "Please refer to to the documentation for full details.%n" +
          "For your reference, known types are: %s", cls.getTypeName(), types );
}
origin: Graylog2/graylog2-server

public TermsStatsResult(TermsAggregation terms, String originalQuery, String builtQuery, long tookMs) {
  super(originalQuery, builtQuery, tookMs);
  this.terms = terms.getBuckets().stream()
    .map(e -> {
      final Map<String, Object> resultMap = Maps.newHashMap();
      resultMap.put("key_field", e.getKey());
      resultMap.put("count", e.getCount());
      final StatsAggregation stats = e.getStatsAggregation(Searches.AGG_STATS);
      resultMap.put("min", stats.getMin());
      resultMap.put("max", stats.getMax());
      resultMap.put("total", stats.getSum());
      resultMap.put("total_count", stats.getCount());
      resultMap.put("mean", stats.getAvg());
      return resultMap;
    })
    .sorted(COMPARATOR)
    .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: neo4j/neo4j

  @SuppressWarnings( "unchecked" )
  @Override
  public <T> T select( Class<T> type, Iterable<? extends T> candidates ) throws IllegalArgumentException
  {
    List<T> sorted = (List<T>) StreamSupport.stream( candidates.spliterator(), false )
        .map( ts -> (Comparable<T>) ts )
        .sorted()
        .collect( Collectors.toList() );

    if ( sorted.isEmpty() )
    {
      throw new IllegalArgumentException( "Could not resolve dependency of type: " +
          type.getName() + ". " + servicesClassPathEntryInformation() );
    }
    return sorted.get( sorted.size() - 1 );
  }
}
origin: prestodb/presto

private List<Expression> getPartitionsAsValuesRows(ShowPartitions showPartitions, QualifiedObjectName table, TableLayout layout)
{
  DiscretePredicates discretePredicates = layout.getDiscretePredicates()
      .orElseThrow(() -> new SemanticException(NOT_SUPPORTED, showPartitions, "Table does not have partition columns: %s", table));
  Map<ColumnHandle, Integer> partitioningColumnIndex = IntStream.range(0, discretePredicates.getColumns().size())
      .boxed()
      .collect(toMap(index -> discretePredicates.getColumns().get(index), index -> index));
  List<TupleDomain<ColumnHandle>> predicates = ImmutableList.copyOf(discretePredicates.getPredicates());
  ImmutableList.Builder<Expression> rowBuilder = ImmutableList.builder();
  for (TupleDomain<ColumnHandle> domain : predicates) {
    List<Expression> row = TupleDomain.extractFixedValues(domain).get()
        .entrySet().stream()
        .sorted(Comparator.comparing(entry -> requireNonNull(partitioningColumnIndex.get(entry.getKey()), "not a partitioning column")))
        .map(Entry::getValue)
        .map(nullableValue -> LiteralInterpreter.toExpression(nullableValue.getValue(), nullableValue.getType()))
        .collect(toImmutableList());
    rowBuilder.add(new Row(row));
  }
  return rowBuilder.build();
}
origin: prestodb/presto

private int updateAssignments(Multimap<String, BucketAssignment> sourceToAllocationChanges)
{
  // perform moves in decreasing order of source node total assigned buckets
  List<String> sourceNodes = sourceToAllocationChanges.asMap().entrySet().stream()
      .sorted((a, b) -> Integer.compare(b.getValue().size(), a.getValue().size()))
      .map(Map.Entry::getKey)
      .collect(toList());
  int moves = 0;
  for (String source : sourceNodes) {
    for (BucketAssignment reassignment : sourceToAllocationChanges.get(source)) {
      // todo: rate-limit new assignments
      shardManager.updateBucketAssignment(reassignment.getDistributionId(), reassignment.getBucketNumber(), reassignment.getNodeIdentifier());
      bucketsBalanced.update(1);
      moves++;
      log.info("Distribution %s: Moved bucket %s from %s to %s",
          reassignment.getDistributionId(),
          reassignment.getBucketNumber(),
          source,
          reassignment.getNodeIdentifier());
    }
  }
  return moves;
}
origin: prestodb/presto

  public List<File> files()
  {
    checkState(location.exists(), "location %s doesn't exist", location);
    if (!pattern.isPresent()) {
      return ImmutableList.of(location);
    }

    checkState(location.isDirectory(), "location %s is not a directory", location);

    try (DirectoryStream<Path> paths = newDirectoryStream(location.toPath(), pattern.get())) {
      ImmutableList.Builder<File> builder = ImmutableList.builder();
      for (Path path : paths) {
        builder.add(path.toFile());
      }
      List<File> files = builder.build();

      if (files.isEmpty()) {
        throw new PrestoException(LOCAL_FILE_NO_FILES, "No matching files found in directory: " + location);
      }
      return files.stream()
          .sorted((o1, o2) -> Long.compare(o2.lastModified(), o1.lastModified()))
          .collect(Collectors.toList());
    }
    catch (IOException e) {
      throw new PrestoException(LOCAL_FILE_FILESYSTEM_ERROR, "Error listing files in directory: " + location, e);
    }
  }
}
origin: neo4j/neo4j

private void verifyLabels( long nodeId, int startLabelIndex, int count )
{
  try ( Transaction tx = dbRule.beginTx() )
  {
    Node node = dbRule.getNodeById( nodeId );
    Set<String> labelNames = Iterables.asList( node.getLabels() )
        .stream()
        .map( Label::name )
        .sorted()
        .collect( toSet() );
    assertEquals( count, labelNames.size() );
    int endLabelIndex = startLabelIndex + count;
    for ( int i = startLabelIndex; i < endLabelIndex; i++ )
    {
      assertTrue( labelNames.contains( labelName( i ) ) );
    }
    tx.success();
  }
}
origin: druid-io/druid

 @VisibleForTesting
 static String[] getFrequentLocations(final Stream<String> locations)
 {
  final Map<String, Long> locationCountMap = locations.collect(
    Collectors.groupingBy(location -> location, Collectors.counting())
  );

  final Comparator<Map.Entry<String, Long>> valueComparator =
    Map.Entry.comparingByValue(Comparator.reverseOrder());

  final Comparator<Map.Entry<String, Long>> keyComparator =
    Map.Entry.comparingByKey();

  return locationCountMap
    .entrySet().stream()
    .sorted(valueComparator.thenComparing(keyComparator))
    .limit(3)
    .map(Map.Entry::getKey)
    .toArray(String[]::new);
 }
}
origin: google/error-prone

private static List<ExecutableElement> getConstructorsWithAnnotations(
  Element exploringConstructor, List<String> annotations) {
 return constructorsIn(exploringConstructor.getEnclosingElement().getEnclosedElements())
   .stream()
   .filter(constructor -> hasAnyOfAnnotation(constructor, annotations))
   .sorted(Comparator.comparing((e -> e.getSimpleName().toString())))
   .collect(toImmutableList());
}
java.util.streamStreamsorted

Javadoc

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.

Popular methods of Stream

  • collect
  • map
  • filter
  • forEach
  • findFirst
  • of
  • anyMatch
  • flatMap
  • toArray
  • count
  • findAny
  • reduce
  • findAny,
  • reduce,
  • allMatch,
  • concat,
  • distinct,
  • mapToInt,
  • iterator,
  • empty,
  • limit

Popular classes and methods

  • getSharedPreferences (Context)
  • setScale (BigDecimal)
    Returns a new BigDecimal instance with the specified scale. If the new scale is greater than the old
  • getResourceAsStream (ClassLoader)
    Returns a stream for the resource with the specified name. See #getResource(String) for a descriptio
  • Selector (java.nio.channels)
    A controller for the selection of SelectableChannel objects. Selectable channels can be registered w
  • Format (java.text)
    Format is an abstract base class for formatting locale-sensitive information such as dates, messages
  • Executor (java.util.concurrent)
    An object that executes submitted Runnable tasks. This interface provides a way of decoupling task s
  • ReentrantLock (java.util.concurrent.locks)
    A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor
  • Reference (javax.naming)
  • Scheduler (org.quartz)
    This is the main interface of a Quartz Scheduler. A Scheduler maintains a registry of org.quartz.Job
  • SAXParseException (org.xml.sax)
    Encapsulate an XML parse error or warning.> This module, both source code and documentation, is in t

For IntelliJ IDEA and
Android Studio

  • Codota IntelliJ IDEA pluginCodota Android Studio pluginCode IndexSign in
  • EnterpriseFAQAboutContact Us
  • Terms of usePrivacy policyCodeboxFind Usages
Add Codota to your IDE (free)