Tabnine Logo
Optional.map
Code IndexAdd Tabnine to your IDE (free)

How to use
map
method
in
java.util.Optional

Best Java code snippets using java.util.Optional.map (Showing top 20 results out of 30,465)

Refine searchRefine arrow

  • Optional.orElse
  • Optional.ofNullable
  • Optional.orElseGet
  • List.stream
  • Optional.isPresent
  • Optional.get
  • Stream.collect
  • Stream.filter
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);
}
java.utilOptionalmap

Javadoc

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.

Popular methods of Optional

  • get
  • orElse
  • isPresent
  • ofNullable
  • empty
  • of
  • ifPresent
  • orElseThrow
  • orElseGet
  • filter
  • flatMap
  • equals
  • flatMap,
  • equals,
  • hashCode,
  • toString,
  • isEmpty,
  • <init>,
  • ifPresentOrElse,
  • or,
  • stream

Popular in Java

  • Parsing JSON documents to java classes using gson
  • setScale (BigDecimal)
  • startActivity (Activity)
  • setRequestProperty (URLConnection)
  • FileInputStream (java.io)
    An input stream that reads bytes from a file. File file = ...finally if (in != null) in.clos
  • FileOutputStream (java.io)
    An output stream that writes bytes to a file. If the output file exists, it can be replaced or appen
  • System (java.lang)
    Provides access to system-related information and resources including standard input and output. Ena
  • LinkedHashMap (java.util)
    LinkedHashMap is an implementation of Map that guarantees iteration order. All optional operations a
  • Random (java.util)
    This class provides methods that return pseudo-random values.It is dangerous to seed Random with the
  • TreeMap (java.util)
    Walk the nodes of the tree left-to-right or right-to-left. Note that in descending iterations, next
  • Github Copilot alternatives
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