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

How to use
ifPresent
method
in
java.util.Optional

Best Java code snippets using java.util.Optional.ifPresent (Showing top 20 results out of 23,544)

Refine searchRefine arrow

  • Optional.ofNullable
  • Stream.filter
  • Optional.isPresent
  • Stream.findFirst
  • List.stream
  • Optional.get
  • Optional.map
origin: prestodb/presto

@Override
public List<Node> getChildren()
{
  ImmutableList.Builder<Node> nodes = ImmutableList.builder();
  window.ifPresent(nodes::add);
  filter.ifPresent(nodes::add);
  orderBy.map(OrderBy::getSortItems).map(nodes::addAll);
  nodes.addAll(arguments);
  return nodes.build();
}
origin: prestodb/presto

public void rollback()
{
  Optional.ofNullable(rollbackAction.getAndSet(null)).ifPresent(Runnable::run);
}
origin: neo4j/neo4j

public void forEach( BiConsumer<String,URI> consumer )
{
  entries.stream().collect( Collectors.groupingBy( e -> e.key ) )
      .forEach( ( key, list ) -> list.stream()
          .max( Comparator.comparing( e -> e.precedence ) )
          .ifPresent( e -> consumer.accept( key, e.uri ) ) );
}
origin: ethereum/ethereumj

public DefaultConfig() {
  Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
    logger.error("Uncaught exception", e);
    FATAL_EXCEPTIONS.stream()
        .filter(errType -> errType.isInstance(e))
        .findFirst()
        .ifPresent(errType -> System.exit(1));
  });
}
origin: prestodb/presto

private void validateSelectors(List<ResourceGroupSpec> groups, SelectorSpec spec)
{
  spec.getQueryType().ifPresent(this::validateQueryType);
  List<ResourceGroupNameTemplate> selectorGroups = spec.getGroup().getSegments();
  StringBuilder fullyQualifiedGroupName = new StringBuilder();
  while (!selectorGroups.isEmpty()) {
    ResourceGroupNameTemplate groupName = selectorGroups.get(0);
    fullyQualifiedGroupName.append(groupName);
    Optional<ResourceGroupSpec> match = groups
        .stream()
        .filter(groupSpec -> groupSpec.getName().equals(groupName))
        .findFirst();
    if (!match.isPresent()) {
      throw new IllegalArgumentException(format("Selector refers to nonexistent group: %s", fullyQualifiedGroupName.toString()));
    }
    fullyQualifiedGroupName.append(".");
    groups = match.get().getSubGroups();
    selectorGroups = selectorGroups.subList(1, selectorGroups.size());
  }
}
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: jenkinsci/jenkins

/**
 * Returns initial {@link Method} as well as all matching ones found in interfaces.
 * This allows to introspect metadata for a method which is both declared in parent class and in implemented
 * interface(s). <code>interfaces</code> typically is obtained by {@link ClassUtils#getAllInterfacesAsSet}
 */
Collection<Method> getMethodAndInterfaceDeclarations(Method method, Collection<Class> interfaces) {
  final List<Method> methods = new ArrayList<>();
  methods.add(method);
  // we search for matching method by iteration and comparison vs getMethod to avoid repeated NoSuchMethodException
  // being thrown, while interface typically only define a few set of methods to check.
  interfaces.stream()
      .map(Class::getMethods)
      .flatMap(Arrays::stream)
      .filter(m -> m.getName().equals(method.getName()) && Arrays.equals(m.getParameterTypes(), method.getParameterTypes()))
      .findFirst()
      .ifPresent(methods::add);
  return methods;
}
origin: prestodb/presto

public String getBearerToken(String subject)
{
  checkState(jwtSigner.isPresent(), "not configured");
  JwtBuilder jwt = Jwts.builder()
      .setSubject(subject)
      .setExpiration(Date.from(ZonedDateTime.now().plusMinutes(5).toInstant()));
  jwtSigner.get().accept(jwt);
  jwtKeyId.ifPresent(keyId -> jwt.setHeaderParam(KEY_ID, keyId));
  jwtIssuer.ifPresent(jwt::setIssuer);
  jwtAudience.ifPresent(jwt::setAudience);
  return jwt.compact();
}
origin: SonarSource/sonarqube

private static void addPullRequest(ProjectPullRequests.ListWsResponse.Builder response, BranchDto branch, Map<String, BranchDto> mergeBranchesByUuid,
 @Nullable LiveMeasureDto qualityGateMeasure, BranchStatistics branchStatistics, @Nullable String analysisDate) {
 Optional<BranchDto> mergeBranch = Optional.ofNullable(mergeBranchesByUuid.get(branch.getMergeBranchUuid()));
 ProjectPullRequests.PullRequest.Builder builder = ProjectPullRequests.PullRequest.newBuilder();
 builder.setKey(branch.getKey());
 DbProjectBranches.PullRequestData pullRequestData = requireNonNull(branch.getPullRequestData(), "Pull request data should be available for branch type PULL_REQUEST");
 builder.setBranch(pullRequestData.getBranch());
 ofNullable(emptyToNull(pullRequestData.getUrl())).ifPresent(builder::setUrl);
 ofNullable(emptyToNull(pullRequestData.getTitle())).ifPresent(builder::setTitle);
 if (mergeBranch.isPresent()) {
  String mergeBranchKey = mergeBranch.get().getKey();
  builder.setBase(mergeBranchKey);
 } else {
  builder.setIsOrphan(true);
 }
 ofNullable(analysisDate).ifPresent(builder::setAnalysisDate);
 setQualityGate(builder, qualityGateMeasure, branchStatistics);
 response.addPullRequests(builder);
}
origin: prestodb/presto

private static void addAllStages(Optional<StageInfo> stageInfo, ImmutableList.Builder<StageInfo> collector)
{
  stageInfo.ifPresent(stage -> {
    collector.add(stage);
    stage.getSubStages().stream()
        .forEach(subStage -> addAllStages(Optional.ofNullable(subStage), collector));
  });
}
origin: prestodb/presto

private void analyzeHaving(QuerySpecification node, Scope scope)
{
  if (node.getHaving().isPresent()) {
    Expression predicate = node.getHaving().get();
    ExpressionAnalysis expressionAnalysis = analyzeExpression(predicate, scope);
    expressionAnalysis.getWindowFunctions().stream()
        .findFirst()
        .ifPresent(function -> {
          throw new SemanticException(NESTED_WINDOW, function.getNode(), "HAVING clause cannot contain window functions");
        });
    analysis.recordSubqueries(node, expressionAnalysis);
    Type predicateType = expressionAnalysis.getType(predicate);
    if (!predicateType.equals(BOOLEAN) && !predicateType.equals(UNKNOWN)) {
      throw new SemanticException(TYPE_MISMATCH, predicate, "HAVING clause must evaluate to a boolean: actual type %s", predicateType);
    }
    analysis.setHaving(node, predicate);
  }
}
origin: prestodb/presto

private void flattenNode(PlanNode node, int limit)
{
  PlanNode resolved = lookup.resolve(node);
  // (limit - 2) because you need to account for adding left and right side
  if (!(resolved instanceof JoinNode) || (sources.size() > (limit - 2))) {
    sources.add(node);
    return;
  }
  JoinNode joinNode = (JoinNode) resolved;
  if (joinNode.getType() != INNER || !isDeterministic(joinNode.getFilter().orElse(TRUE_LITERAL)) || joinNode.getDistributionType().isPresent()) {
    sources.add(node);
    return;
  }
  // we set the left limit to limit - 1 to account for the node on the right
  flattenNode(joinNode.getLeft(), limit - 1);
  flattenNode(joinNode.getRight(), limit);
  joinNode.getCriteria().stream()
      .map(EquiJoinClause::toExpression)
      .forEach(filters::add);
  joinNode.getFilter().ifPresent(filters::add);
}
origin: prestodb/presto

public static void checkTableName(String catalogName, Optional<String> schemaName, Optional<String> tableName)
{
  checkCatalogName(catalogName);
  schemaName.ifPresent(name -> checkLowerCase(name, "schemaName"));
  tableName.ifPresent(name -> checkLowerCase(name, "tableName"));
  checkArgument(schemaName.isPresent() || !tableName.isPresent(), "tableName specified but schemaName is missing");
}
origin: SonarSource/sonarqube

private static void writeIfNeeded(String fieldName, @Nullable Date value, Consumer<String> setter, Set<String> desiredFields) {
 if (desiredFields.contains(fieldName)) {
  ofNullable(value).map(DateUtils::formatDateTime).ifPresent(setter);
 }
}
origin: rest-assured/rest-assured

private Object[] resolvePathParams(Object[] pathParams) {
  Arrays.stream(pathParams).filter(param -> !(param instanceof String))
      .findAny().ifPresent(param -> {
    throw new IllegalArgumentException("Only Strings allowed in path parameters.");
  });
  return Arrays.stream(pathParams)
      .map(param -> UriUtils.encode((String) param, Charsets.UTF_8)).toArray();
}
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: SonarSource/sonarqube

private List<Setting> loadSettings(DbSession dbSession, Optional<ComponentDto> component, Set<String> keys) {
 // List of settings must be kept in the following orders : default -> global -> component -> branch
 List<Setting> settings = new ArrayList<>();
 settings.addAll(loadDefaultValues(keys));
 settings.addAll(loadGlobalSettings(dbSession, keys));
 if (component.isPresent() && component.get().getBranch() != null && component.get().getMainBranchProjectUuid() != null) {
  ComponentDto project = dbClient.componentDao().selectOrFailByUuid(dbSession, component.get().getMainBranchProjectUuid());
  settings.addAll(loadComponentSettings(dbSession, keys, project).values());
 }
 component.ifPresent(componentDto -> settings.addAll(loadComponentSettings(dbSession, keys, componentDto).values()));
 return settings.stream()
  .filter(s -> settingsWsSupport.isVisible(s.getKey(), s.getDefinition(), component))
  .collect(Collectors.toList());
}
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: apache/flink

/**
 * Validates that the given prefix is not included in these properties.
 */
public void validatePrefixExclusion(String prefix) {
  properties.keySet().stream()
    .filter(k -> k.startsWith(prefix))
    .findFirst()
    .ifPresent((k) -> {
      throw new ValidationException(
        "Properties with prefix '" + prefix + "' are not allowed in this context. " +
        "But property '" + k + "' was found.");
    });
}
origin: SonarSource/sonarqube

private List<String> getValues() {
 Optional<String> value = readParam("value");
 if (!value.isPresent()) {
  List<String> values = new ArrayList<>();
  readBody().ifPresent(values::add);
  return values;
 }
 return VALUE_SPLITTER.splitToList(value.get());
}
java.utilOptionalifPresent

Javadoc

If a value is present, invoke the specified consumer with the value, otherwise do nothing.

Popular methods of Optional

  • get
  • orElse
  • isPresent
  • ofNullable
  • empty
  • of
  • map
  • 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
  • Top Sublime Text 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