Tabnine Logo
Stream.filter
Code IndexAdd Tabnine to your IDE (free)

How to use
filter
method
in
java.util.stream.Stream

Best Java code snippets using java.util.stream.Stream.filter (Showing top 20 results out of 71,244)

Refine searchRefine arrow

  • Stream.collect
  • List.stream
  • Collectors.toList
  • Stream.map
  • Collectors.toSet
  • Stream.findFirst
  • Optional.orElse
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());
}
origin: apache/incubator-dubbo

private <T> List<Invoker<T>> filterInvoker(List<Invoker<T>> invokers, Predicate<Invoker<T>> predicate) {
  return invokers.stream()
      .filter(predicate)
      .collect(Collectors.toList());
}
origin: spring-projects/spring-framework

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

/**
 * Return method model for the given method on consumer side
 *
 * @param method method object
 * @return method model
 */
public ConsumerMethodModel getMethodModel(String method) {
  Optional<Map.Entry<Method, ConsumerMethodModel>> consumerMethodModelEntry = methodModels.entrySet().stream().filter(entry -> entry.getKey().getName().equals(method)).findFirst();
  return consumerMethodModelEntry.map(Map.Entry::getValue).orElse(null);
}
origin: prestodb/presto

private static <T> Set<T> intersect(Set<T> set1, Set<T> set2)
{
  return set1.stream()
      .filter(set2::contains)
      .collect(toSet());
}
origin: spring-projects/spring-framework

private static <T, S extends Publisher<T>> S readWithMessageReaders(
    ReactiveHttpInputMessage message, BodyExtractor.Context context, ResolvableType elementType,
    Function<HttpMessageReader<T>, S> readerFunction,
    Function<UnsupportedMediaTypeException, S> errorFunction,
    Supplier<S> emptySupplier) {
  if (VOID_TYPE.equals(elementType)) {
    return emptySupplier.get();
  }
  MediaType contentType = Optional.ofNullable(message.getHeaders().getContentType())
      .orElse(MediaType.APPLICATION_OCTET_STREAM);
  return context.messageReaders().stream()
      .filter(reader -> reader.canRead(elementType, contentType))
      .findFirst()
      .map(BodyExtractors::<T>cast)
      .map(readerFunction)
      .orElseGet(() -> {
        List<MediaType> mediaTypes = context.messageReaders().stream()
            .flatMap(reader -> reader.getReadableMediaTypes().stream())
            .collect(Collectors.toList());
        return errorFunction.apply(
            new UnsupportedMediaTypeException(contentType, mediaTypes, elementType));
      });
}
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: spring-projects/spring-framework

/**
 * Return declared "producible" types but only among those that also
 * match the "methods" and "consumes" conditions.
 */
public Set<MediaType> getProducibleMediaTypes() {
  return this.partialMatches.stream().filter(PartialMatch::hasConsumesMatch).
      flatMap(m -> m.getInfo().getProducesCondition().getProducibleMediaTypes().stream()).
      collect(Collectors.toCollection(LinkedHashSet::new));
}
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

/**
 * Get all methods in the supplied {@link Class class} and its superclasses
 * which are annotated with the supplied {@code annotationType} but
 * which are not <em>shadowed</em> by methods overridden in subclasses.
 * <p>Default methods on interfaces are also detected.
 * @param clazz the class for which to retrieve the annotated methods
 * @param annotationType the annotation type for which to search
 * @return all annotated methods in the supplied class and its superclasses
 * as well as annotated interface default methods
 */
private List<Method> getAnnotatedMethods(Class<?> clazz, Class<? extends Annotation> annotationType) {
  return Arrays.stream(ReflectionUtils.getUniqueDeclaredMethods(clazz))
      .filter(method -> AnnotatedElementUtils.hasAnnotation(method, annotationType))
      .collect(Collectors.toList());
}
origin: spring-projects/spring-framework

private static <T> HttpMessageWriter<T> findWriter(
    BodyInserter.Context context, ResolvableType elementType, @Nullable MediaType mediaType) {
  return context.messageWriters().stream()
      .filter(messageWriter -> messageWriter.canWrite(elementType, mediaType))
      .findFirst()
      .map(BodyInserters::<T>cast)
      .orElseThrow(() -> new IllegalStateException(
          "No HttpMessageWriter for \"" + mediaType + "\" and \"" + elementType + "\""));
}
origin: jenkinsci/jenkins

private @Nonnull Optional<SingleTokenStats> findById(@Nonnull String tokenUuid) {
  return tokenStats.stream()
      .filter(s -> s.tokenUuid.equals(tokenUuid))
      .findFirst();
}

origin: apache/incubator-dubbo

  public static int getConsumerAddressNum(String serviceUniqueName) {
    Set<ConsumerInvokerWrapper> providerInvokerWrapperSet = ProviderConsumerRegTable.getConsumerInvoker(serviceUniqueName);
    return providerInvokerWrapperSet.stream()
        .map(w -> w.getRegistryDirectory().getUrlInvokerMap())
        .filter(Objects::nonNull)
        .mapToInt(Map::size).sum();
  }
}
origin: spring-projects/spring-framework

@Override
public Stream<T> stream() {
  return Arrays.stream(getBeanNamesForTypedStream(requiredType))
      .map(name -> (T) getBean(name))
      .filter(bean -> !(bean instanceof NullBean));
}
@Override
origin: spring-projects/spring-framework

private Mono<Map<String, Object>> initAttributes(ServerWebExchange exchange) {
  if (this.sessionAttributePredicate == null) {
    return EMPTY_ATTRIBUTES;
  }
  return exchange.getSession().map(session ->
      session.getAttributes().entrySet().stream()
          .filter(entry -> this.sessionAttributePredicate.test(entry.getKey()))
          .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
}
origin: spring-projects/spring-framework

private static Method getMethodForReturnType(Class<?> returnType) {
  return Arrays.stream(TestBean.class.getMethods())
      .filter(method -> method.getReturnType().equals(returnType))
      .findFirst()
      .orElseThrow(() ->
          new IllegalArgumentException("Unique return type not found: " + returnType));
}
origin: spring-projects/spring-framework

@Override
public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
  // Remove underlying context path first (e.g. Servlet container)
  String path = request.getPath().pathWithinApplication().value();
  return this.handlerMap.entrySet().stream()
      .filter(entry -> path.startsWith(entry.getKey()))
      .findFirst()
      .map(entry -> {
        String contextPath = request.getPath().contextPath().value() + entry.getKey();
        ServerHttpRequest newRequest = request.mutate().contextPath(contextPath).build();
        return entry.getValue().handle(newRequest, response);
      })
      .orElseGet(() -> {
        response.setStatusCode(HttpStatus.NOT_FOUND);
        return response.setComplete();
      });
}
origin: apache/kafka

  private KafkaMetric getMetric(String name) throws Exception {
    Optional<Map.Entry<MetricName, KafkaMetric>> metric = metrics.metrics().entrySet().stream()
        .filter(entry -> entry.getKey().name().equals(name))
        .findFirst();
    if (!metric.isPresent())
      throw new Exception(String.format("Could not find metric called %s", name));

    return metric.get().getValue();
  }
}
origin: apache/incubator-dubbo

private <T> List<Invoker<T>> filterInvoker(List<Invoker<T>> invokers, Predicate<Invoker<T>> predicate) {
  return invokers.stream()
      .filter(predicate)
      .collect(Collectors.toList());
}
origin: spring-projects/spring-framework

private static Log initLogger(List<Log> loggers, Predicate<Log> predicate) {
  return loggers.stream().filter(predicate).findFirst().orElse(NO_OP_LOG);
}
java.util.streamStreamfilter

Javadoc

Returns a stream consisting of the elements of this stream that match the given predicate.

This is an intermediate operation.

Popular methods of Stream

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

Popular in Java

  • Reading from database using SQL prepared statement
  • addToBackStack (FragmentTransaction)
  • setRequestProperty (URLConnection)
  • startActivity (Activity)
  • BufferedImage (java.awt.image)
    The BufferedImage subclass describes an java.awt.Image with an accessible buffer of image data. All
  • Runnable (java.lang)
    Represents a command that can be executed. Often used to run code in a different Thread.
  • HttpURLConnection (java.net)
    An URLConnection for HTTP (RFC 2616 [http://tools.ietf.org/html/rfc2616]) used to send and receive d
  • URLEncoder (java.net)
    This class is used to encode a string using the format required by application/x-www-form-urlencoded
  • TimeUnit (java.util.concurrent)
    A TimeUnit represents time durations at a given unit of granularity and provides utility methods to
  • BoxLayout (javax.swing)
  • Top plugins for WebStorm
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now