本文整理了Java中java.util.stream.Stream.filter()
方法的一些代码示例,展示了Stream.filter()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Stream.filter()
方法的具体详情如下:
包路径:java.util.stream.Stream
类名称:Stream
方法名:filter
[英]Returns a stream consisting of the elements of this stream that match the given predicate.
This is an intermediate operation.
[中]返回一个流,该流包含与给定谓词匹配的该流元素。
这是一个intermediate operation。
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);
}
内容来源于网络,如有侵权,请联系作者删除!