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

How to use
ofNullable
method
in
java.util.Optional

Best Java code snippets using java.util.Optional.ofNullable (Showing top 20 results out of 40,050)

Refine searchRefine arrow

  • Optional.orElse
  • Optional.map
  • Map.get
  • Optional.empty
  • JsonProperty.<init>
  • Optional.orElseGet
  • Optional.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: iluwatar/java-design-patterns

@Override
public Optional<Customer> getById(final int id) {
 return Optional.ofNullable(idToCustomer.get(id));
}
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: dropwizard/dropwizard

@Override
@JsonProperty
public Optional<Duration> getValidationQueryTimeout() {
  return Optional.ofNullable(validationQueryTimeout);
}
origin: dropwizard/dropwizard

@Override
public void configure(Map<String, String> options) {
  useCache = Optional.ofNullable(options.get("cache")).map(Boolean::parseBoolean).orElse(true);
  fileRoot = Optional.ofNullable(options.get("fileRoot")).map(File::new);
}
origin: Netflix/eureka

/**
 * Gets the list of <em>instances</em> associated to a virtual host name.
 *
 * @param virtualHostName
 *            the virtual hostname for which the instances need to be
 *            returned.
 * @return list of <em>instances</em>.
 */
public List<InstanceInfo> getInstancesByVirtualHostName(String virtualHostName) {
  return Optional.ofNullable(this.virtualHostNameAppMap.get(virtualHostName.toUpperCase(Locale.ROOT)))
    .map(VipIndexSupport::getVipList)
    .map(AtomicReference::get)
    .orElseGet(Collections::emptyList); 
}
origin: gocd/gocd

private Optional<String> parseTag(ProcessType requestType, LogLevel logLevel) {
  switch (requestType) {
    case FETCH:
      return Optional.ofNullable(FETCH_ARTIFACT_LOG_LEVEL_TAG.get(logLevel));
    case PUBLISH:
      return Optional.ofNullable(PUBLISH_ARTIFACT_LOG_LEVEL_TAG.get(logLevel));
  }
  return Optional.empty();
}
origin: hs-web/hsweb-framework

  public Optional<String> getStringConfig(String name) {
    return config == null ?
        Optional.empty() :
        Optional.ofNullable(config.get(name))
            .map(String::valueOf);
  }
}
origin: apache/kafka

Optional<PartitionInfo> getPartitionInfo(TopicPartition topicPartition) {
  return Optional.ofNullable(metadataByPartition.get(topicPartition))
      .map(PartitionInfoAndEpoch::partitionInfo);
}
origin: prestodb/presto

public List<GroupingOperation> getGroupingOperations(QuerySpecification querySpecification)
{
  return Optional.ofNullable(groupingOperations.get(NodeRef.of(querySpecification)))
      .orElse(emptyList());
}
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: apache/flink

public <R> Optional<R> map(Function<? super T, ? extends R> mapper) {
  if (value == null) {
    return Optional.empty();
  } else {
    return Optional.ofNullable(mapper.apply(value));
  }
}
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 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

private Optional<QueryFailureInfo> createQueryFailureInfo(ExecutionFailureInfo failureInfo, Optional<StageInfo> outputStage)
{
  if (failureInfo == null) {
    return Optional.empty();
  }
  Optional<TaskInfo> failedTask = outputStage.flatMap(QueryMonitor::findFailedTask);
  return Optional.of(new QueryFailureInfo(
      failureInfo.getErrorCode(),
      Optional.ofNullable(failureInfo.getType()),
      Optional.ofNullable(failureInfo.getMessage()),
      failedTask.map(task -> task.getTaskStatus().getTaskId().toString()),
      failedTask.map(task -> task.getTaskStatus().getSelf().getHost()),
      executionFailureInfoCodec.toJson(failureInfo)));
}
origin: spring-projects/spring-framework

private String getNameForReturnValue(MethodParameter returnType) {
  return Optional.ofNullable(returnType.getMethodAnnotation(ModelAttribute.class))
      .filter(ann -> StringUtils.hasText(ann.value()))
      .map(ModelAttribute::value)
      .orElseGet(() -> Conventions.getVariableNameForParameter(returnType));
}
origin: perwendel/spark

public static String fromResource(AbstractFileResolvingResource resource) {
  String filename = Optional.ofNullable(resource.getFilename()).orElse("");
  return getMimeType(filename);
}
origin: SonarSource/sonarqube

private RuleUpdate createRuleUpdate(DbSession dbSession, RuleKey key, OrganizationDto organization) {
 RuleDto rule = dbClient.ruleDao().selectByKey(dbSession, organization, key)
  .orElseThrow(() -> new NotFoundException(format("This rule does not exist: %s", key)));
 RuleUpdate ruleUpdate = ofNullable(rule.getTemplateId())
  .map(x -> RuleUpdate.createForCustomRule(key))
  .orElseGet(() -> RuleUpdate.createForPluginRule(key));
 ruleUpdate.setOrganization(organization);
 return ruleUpdate;
}
origin: Netflix/eureka

/**
 * Gets the list of instances associated with this particular application.
 * <p>
 * Note that the instances are always returned with random order after
 * shuffling to avoid traffic to the same instances during startup. The
 * shuffling always happens once after every fetch cycle as specified in
 * {@link EurekaClientConfig#getRegistryFetchIntervalSeconds}.
 * </p>
 *
 * @return the list of shuffled instances associated with this application.
 */
@JsonProperty("instance")
public List<InstanceInfo> getInstances() {
  return Optional.ofNullable(shuffledInstances.get()).orElseGet(this::getInstancesAsIsFromEureka);
}
origin: jenkinsci/jenkins

private static void makeRemovable(@Nonnull Path path) throws IOException {
  if (!Files.isWritable(path)) {
    makeWritable(path);
  }
  /*
   on Unix both the file and the directory that contains it has to be writable
   for a file deletion to be successful. (Confirmed on Solaris 9)
   $ ls -la
   total 6
   dr-xr-sr-x   2 hudson   hudson       512 Apr 18 14:41 .
   dr-xr-sr-x   3 hudson   hudson       512 Apr 17 19:36 ..
   -r--r--r--   1 hudson   hudson       469 Apr 17 19:36 manager.xml
   -rw-r--r--   1 hudson   hudson         0 Apr 18 14:41 x
   $ rm x
   rm: x not removed: Permission denied
   */
  Optional<Path> maybeParent = Optional.ofNullable(path.getParent()).map(Path::normalize).filter(p -> !Files.isWritable(p));
  if (maybeParent.isPresent()) {
    makeWritable(maybeParent.get());
  }
}
java.utilOptionalofNullable

Javadoc

Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.

Popular methods of Optional

  • get
  • orElse
  • isPresent
  • empty
  • of
  • map
  • 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
  • getContentResolver (Context)
  • notifyDataSetChanged (ArrayAdapter)
  • scheduleAtFixedRate (Timer)
  • FileInputStream (java.io)
    An input stream that reads bytes from a file. File file = ...finally if (in != null) in.clos
  • HttpURLConnection (java.net)
    An URLConnection for HTTP (RFC 2616 [http://tools.ietf.org/html/rfc2616]) used to send and receive d
  • Arrays (java.util)
    This class contains various methods for manipulating arrays (such as sorting and searching). This cl
  • DataSource (javax.sql)
    An interface for the creation of Connection objects which represent a connection to a database. This
  • IsNull (org.hamcrest.core)
    Is the value null?
  • Reflections (org.reflections)
    Reflections one-stop-shop objectReflections scans your classpath, indexes the metadata, allows you t
  • Best IntelliJ plugins
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