java.util.Optional.map()方法的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(9.7k)|赞(0)|评价(0)|浏览(612)

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

Optional.map介绍

[英]If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.
[中]如果存在值,则对其应用提供的映射函数,如果结果为非null,则返回描述结果的可选值。否则,返回一个空的可选值。

代码示例

canonical example by Tabnine

private Double calculateAverageGrade(Map<String, List<Integer>> gradesList, String studentName)
  throws Exception {
 return Optional.ofNullable(gradesList.get(studentName))
   .map(list -> list.stream().collect(Collectors.averagingDouble(x -> x)))
   .orElseThrow(() -> new Exception("Student not found - " + studentName));
}

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

@Override
public OptionalDouble getValueFromAggregationQueryResult(Object value)
{
  return Optional.ofNullable(value)
      .map(Number.class::cast)
      .map(Number::doubleValue)
      .map(OptionalDouble::of)
      .orElseGet(OptionalDouble::empty);
}

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

private String getCharset() {
  return Optional.of(this.bodySpec.returnResult())
      .map(EntityExchangeResult::getResponseHeaders)
      .map(HttpHeaders::getContentType)
      .map(MimeType::getCharset)
      .orElse(StandardCharsets.UTF_8)
      .name();
}

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

/**
 * Determine a media type for the given resource, if possible.
 * @param resource the resource to introspect
 * @return the corresponding media type, or {@code null} if none found
 */
public static Optional<MediaType> getMediaType(@Nullable Resource resource) {
  return Optional.ofNullable(resource)
      .map(Resource::getFilename)
      .flatMap(MediaTypeFactory::getMediaType);
}

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

@VisibleForTesting
static Estimate calculateDistinctValuesCount(List<HiveColumnStatistics> columnStatistics)
{
  return columnStatistics.stream()
      .map(MetastoreHiveStatisticsProvider::getDistinctValuesCount)
      .filter(OptionalLong::isPresent)
      .map(OptionalLong::getAsLong)
      .peek(distinctValuesCount -> verify(distinctValuesCount >= 0, "distinctValuesCount must be greater than or equal to zero"))
      .max(Long::compare)
      .map(Estimate::of)
      .orElse(Estimate.unknown());
}

代码示例来源: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: prestodb/presto

public Node<E> findLeaf()
{
  int leftDecendants = left.map(node -> node.descendants).orElse(0);
  int rightDecendants = right.map(node -> node.descendants).orElse(0);
  if (leftDecendants == 0 && rightDecendants == 0) {
    return left.orElse(right.orElse(this));
  }
  if (leftDecendants > rightDecendants) {
    return left.get().findLeaf();
  }
  if (rightDecendants > leftDecendants) {
    return right.get().findLeaf();
  }
  // For ties just go left
  checkState(left.isPresent(), "Left child missing");
  return left.get().findLeaf();
}

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

/**
 * Determine the media types for the given file name, if possible.
 * @param filename the file name plus extension
 * @return the corresponding media types, or an empty list if none found
 */
public static List<MediaType> getMediaTypes(@Nullable String filename) {
  return Optional.ofNullable(StringUtils.getFilenameExtension(filename))
      .map(s -> s.toLowerCase(Locale.ENGLISH))
      .map(fileExtensionToMediaTypes::get)
      .orElse(Collections.emptyList());
}

代码示例来源: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);
}

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

private ConnectorBucketNodeMap(int bucketCount, Optional<List<Node>> bucketToNode)
{
  if (bucketCount <= 0) {
    throw new IllegalArgumentException("bucketCount must be positive");
  }
  if (bucketToNode.isPresent() && bucketToNode.get().size() != bucketCount) {
    throw new IllegalArgumentException(format("Mismatched bucket count in bucketToNode (%s) and bucketCount (%s)", bucketToNode.get().size(), bucketCount));
  }
  this.bucketCount = bucketCount;
  this.bucketToNode = bucketToNode.map(ArrayList::new).map(Collections::unmodifiableList);
}

代码示例来源: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: 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: prestodb/presto

public Type[] getRelationCoercion(Relation relation)
{
  return Optional.ofNullable(relationCoercions.get(NodeRef.of(relation)))
      .map(types -> types.stream().toArray(Type[]::new))
      .orElse(null);
}

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

private static Optional<Domain> getPathDomain(TupleDomain<HiveColumnHandle> effectivePredicate)
{
  if (!effectivePredicate.getDomains().isPresent()) {
    return Optional.empty();
  }
  return effectivePredicate.getDomains().get().entrySet().stream()
      .filter(entry -> isPathColumnHandle(entry.getKey()))
      .findFirst()
      .map(Map.Entry::getValue);
}

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

private static <P extends Publisher<?>, M extends ReactiveHttpOutputMessage> Mono<Void> writeWithMessageWriters(
    M outputMessage, BodyInserter.Context context, P body, ResolvableType bodyType) {
  MediaType mediaType = outputMessage.getHeaders().getContentType();
  return context.messageWriters().stream()
      .filter(messageWriter -> messageWriter.canWrite(bodyType, mediaType))
      .findFirst()
      .map(BodyInserters::cast)
      .map(writer -> write(body, bodyType, mediaType, outputMessage, context, writer))
      .orElseGet(() -> Mono.error(unsupportedError(bodyType, context, mediaType)));
}

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

private static boolean isQGStatusUnchanged(QGChangeEvent qualityGateEvent, Optional<EvaluatedQualityGate> evaluatedQualityGate) {
 Optional<Metric.Level> previousStatus = qualityGateEvent.getPreviousStatus();
 if (!previousStatus.isPresent() && !evaluatedQualityGate.isPresent()) {
  return true;
 }
 return previousStatus
  .map(previousQGStatus -> evaluatedQualityGate
   .filter(newQualityGate -> newQualityGate.getStatus() == previousQGStatus)
   .isPresent())
  .orElse(false);
}

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

private <T> List<T> parseMatchers( String configName, Config config, String delimiter, Function<String,T>
    matchFunc )
{
  String fullAccessProcedures = config.getValue( configName ).map( Object::toString ).orElse( "" );
  if ( fullAccessProcedures.isEmpty() )
  {
    return Collections.emptyList();
  }
  else
  {
    return Stream.of( fullAccessProcedures.split( delimiter ) ).map( matchFunc )
        .collect( Collectors.toList() );
  }
}

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

private static OptionalLong getTableParameterValue(QueryResult describeResult, String key)
{
  verify(describeResult.getColumnsCount() == 3, "describe result is expected to have 3 columns");
  for (List<Object> row : describeResult.rows()) {
    Optional<String> parameterKey = Optional.ofNullable(row.get(1))
        .map(Object::toString)
        .map(String::trim);
    if (parameterKey.isPresent() && key.equals(parameterKey.get())) {
      return Optional.ofNullable(row.get(2))
          .map(Object::toString)
          .map(String::trim)
          .map(TestHiveBasicTableStatistics::tryParse)
          .get();
    }
  }
  return OptionalLong.empty();
}

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

/**
 * Checks whether all of the data buffers allocated by this factory have also been released.
 * If not, then an {@link AssertionError} is thrown. Typically used from a JUnit {@link After}
 * method.
 */
public void checkForLeaks() {
  this.created.stream()
      .filter(LeakAwareDataBuffer::isAllocated)
      .findFirst()
      .map(LeakAwareDataBuffer::leakError)
      .ifPresent(leakError -> {
        throw leakError;
      });
}

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

/**
 * Return the first {@link Locale} of the content languages,
 * as specified by the {@literal Content-Language} header.
 * <p>Returns {@code null} when the content language is unknown.
 * <p>Use {@code getValuesAsList(CONTENT_LANGUAGE)} if you need
 * to get multiple content languages.</p>
 * @since 5.0
 */
@Nullable
public Locale getContentLanguage() {
  return getValuesAsList(CONTENT_LANGUAGE)
      .stream()
      .findFirst()
      .map(Locale::forLanguageTag)
      .orElse(null);
}

相关文章