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

How to use
orElse
method
in
java.util.Optional

Best Java code snippets using java.util.Optional.orElse (Showing top 20 results out of 47,826)

Refine searchRefine arrow

  • Stream.findFirst
  • Stream.filter
  • Stream.of
  • Optional.map
  • Optional.ofNullable
  • List.stream
  • Stream.map
origin: spring-projects/spring-framework

@Nullable
private static MediaType initDefaultMediaType(List<MediaType> mediaTypes) {
  return mediaTypes.stream().filter(MediaType::isConcrete).findFirst().orElse(null);
}
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: 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

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: apache/incubator-druid

 @Override
 @Nullable
 public Long getLockId(String entryId, LockType lock)
 {
  return getLocks(entryId).entrySet().stream()
              .filter(entry -> entry.getValue().equals(lock))
              .map(Entry::getKey)
              .findAny()
              .orElse(null);
 }
}
origin: apache/incubator-dubbo

@Override
public synchronized void notify(List<URL> urls) {
  List<URL> categoryUrls = urls.stream()
      .filter(this::isValidCategory)
      .filter(this::isNotCompatibleFor26x)
      .collect(Collectors.toList());
  /**
   * TODO Try to refactor the processing of these three type of urls using Collectors.groupBy()?
   */
  this.configurators = Configurator.toConfigurators(classifyUrls(categoryUrls, UrlUtils::isConfigurator))
      .orElse(configurators);
  toRouters(classifyUrls(categoryUrls, UrlUtils::isRoute)).ifPresent(this::addRouters);
  // providers
  refreshOverrideAndInvoker(classifyUrls(categoryUrls, UrlUtils::isProvider));
}
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: apache/incubator-druid

@Nullable
MonitorEntry getRunningTaskMonitorEntry(String subTaskSpecId)
{
 return runningTasks.values()
           .stream()
           .filter(monitorEntry -> monitorEntry.spec.getId().equals(subTaskSpecId))
           .findFirst()
           .orElse(null);
}
origin: spring-projects/spring-framework

@Override
public WebClient build() {
  ExchangeFunction exchange = initExchangeFunction();
  ExchangeFunction filteredExchange = (this.filters != null ? this.filters.stream()
      .reduce(ExchangeFilterFunction::andThen)
      .map(filter -> filter.apply(exchange))
      .orElse(exchange) : exchange);
  return new DefaultWebClient(filteredExchange, initUriBuilderFactory(),
      this.defaultHeaders != null ? unmodifiableCopy(this.defaultHeaders) : null,
      this.defaultCookies != null ? unmodifiableCopy(this.defaultCookies) : null,
      this.defaultRequest, new DefaultWebClientBuilder(this));
}
origin: SonarSource/sonarqube

private void validatePullRequestParamsWhenPluginAbsent(List<String> validationMessages) {
 Stream.of(PULL_REQUEST_KEY, PULL_REQUEST_BRANCH, PULL_REQUEST_BASE)
  .filter(param -> nonNull(settings.get(param).orElse(null)))
  .forEach(param -> validationMessages.add(format("To use the property \"%s\", the branch plugin is required but not installed. "
   + "See the documentation of branch support: %s.", param, BRANCHES_DOC_LINK)));
}
origin: prestodb/presto

public List<GroupingOperation> getGroupingOperations(QuerySpecification querySpecification)
{
  return Optional.ofNullable(groupingOperations.get(NodeRef.of(querySpecification)))
      .orElse(emptyList());
}
origin: baomidou/mybatis-plus

public Resource[] resolveMapperLocations() {
  return Stream.of(Optional.ofNullable(this.mapperLocations).orElse(new String[0]))
    .flatMap(location -> Stream.of(getResources(location)))
    .toArray(Resource[]::new);
}
origin: prestodb/presto

  @Override
  public Result apply(SemiJoinNode semiJoinNode, Captures captures, Context context)
  {
    Set<Symbol> requiredFilteringSourceInputs = Streams.concat(
        Stream.of(semiJoinNode.getFilteringSourceJoinSymbol()),
        semiJoinNode.getFilteringSourceHashSymbol().map(Stream::of).orElse(Stream.empty()))
        .collect(toImmutableSet());

    return restrictOutputs(context.getIdAllocator(), semiJoinNode.getFilteringSource(), requiredFilteringSourceInputs)
        .map(newFilteringSource ->
            semiJoinNode.replaceChildren(ImmutableList.of(semiJoinNode.getSource(), newFilteringSource)))
        .map(Result::ofPlanNode)
        .orElse(Result.empty());
  }
}
origin: lets-blade/blade

/**
 * register route to container
 */
public void register() {
  routes.values().forEach(route -> logAddRoute(log, route));
  hooks.values().stream().flatMap(Collection::stream).forEach(route -> logAddRoute(log, route));
  Stream.of(routes.values(), hooks.values().stream().findAny().orElse(new ArrayList<>()))
      .flatMap(Collection::stream).forEach(this::registerRoute);
  regexMapping.register();
  webSockets.keySet().forEach(path -> logWebSocket(log, path));
}
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);
}
origin: spring-projects/spring-framework

private Charset getCharset() {
  return Optional.ofNullable(this.headers.getContentType())
      .map(MimeType::getCharset).orElse(StandardCharsets.UTF_8);
}
origin: hs-web/hsweb-framework

public boolean putCreatorId(OwnCreatedDataAccessConfig access, AuthorizingContext context) {
  RecordCreationEntity entity = context.getParamContext().getParams()
      .values().stream()
      .filter(RecordCreationEntity.class::isInstance)
      .map(RecordCreationEntity.class::cast)
      .findAny().orElse(null);
  if (entity != null) {
    entity.setCreatorId(context.getAuthentication().getUser().getId());
  } else {
    logger.warn("try put creatorId property,but not found any RecordCreationEntity!");
  }
  return true;
}
origin: apache/incubator-dubbo

@Override
public synchronized void notify(List<URL> urls) {
  List<URL> categoryUrls = urls.stream()
      .filter(this::isValidCategory)
      .filter(this::isNotCompatibleFor26x)
      .collect(Collectors.toList());
  /**
   * TODO Try to refactor the processing of these three type of urls using Collectors.groupBy()?
   */
  this.configurators = Configurator.toConfigurators(classifyUrls(categoryUrls, UrlUtils::isConfigurator))
      .orElse(configurators);
  toRouters(classifyUrls(categoryUrls, UrlUtils::isRoute)).ifPresent(this::addRouters);
  // providers
  refreshOverrideAndInvoker(classifyUrls(categoryUrls, UrlUtils::isProvider));
}
origin: spring-projects/spring-framework

/**
 * A shortcut for creating a {@code ResponseEntity} with the given body
 * and the {@linkplain HttpStatus#OK OK} status, or an empty body and a
 * {@linkplain HttpStatus#NOT_FOUND NOT FOUND} status in case of a
 * {@linkplain Optional#empty()} parameter.
 * @return the created {@code ResponseEntity}
 * @since 5.1
 */
public static <T> ResponseEntity<T> of(Optional<T> body) {
  Assert.notNull(body, "Body must not be null");
  return body.map(ResponseEntity::ok).orElse(notFound().build());
}
origin: perwendel/spark

public static String fromResource(AbstractFileResolvingResource resource) {
  String filename = Optional.ofNullable(resource.getFilename()).orElse("");
  return getMimeType(filename);
}
java.utilOptionalorElse

Javadoc

Return the value if present, otherwise return other.

Popular methods of Optional

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

Popular in Java

  • Reactive rest calls using spring rest template
  • orElseThrow (Optional)
    Return the contained value, if present, otherwise throw an exception to be created by the provided s
  • setContentView (Activity)
  • onRequestPermissionsResult (Fragment)
  • 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