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

How to use
filter
method
in
java.util.Optional

Best Java code snippets using java.util.Optional.filter (Showing top 20 results out of 7,272)

Refine searchRefine arrow

  • Optional.map
  • Optional.ofNullable
  • Optional.isPresent
  • Optional.orElse
  • Optional.ifPresent
origin: spring-projects/spring-framework

@Override
public boolean test(ServerRequest request) {
  Optional<String> s = request.queryParam(this.name);
  return s.filter(this.valuePredicate).isPresent();
}
origin: siacs/Conversations

@Override
public final byte[] get(final Object key) {
  return Optional.ofNullable(key).map(Object::toString).filter(((Predicate<String>) String::isEmpty).negate()).map(cacheDirectory::resolve).filter(Files::isReadable).map(file -> {
    try {
      return Files.readAllBytes(file);
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }
  }).orElse(null);
}
origin: SonarSource/sonarqube

@Override
public boolean isExecutedBy(Thread thread) {
 return Optional.ofNullable(runningState.get())
  .filter(state -> state.runningThread.equals(thread))
  .isPresent();
}
origin: spring-projects/spring-data-jpa

@Override
public Class<?> getUserType(Class<?> type) {
  return HIBERNATE_PROXY //
      .map(it -> it.isAssignableFrom(type) ? type.getSuperclass() : type) //
      .filter(it -> !Object.class.equals(it)) //
      .orElse(type);
}
origin: SonarSource/sonarqube

 @Override
 public void handleResult(ResultContext<? extends IssueDto> resultContext) {
  IssueDto resultObject = resultContext.getResultObject();
  // issue are ordered by most recent change first, only the first row for a given issue is of interest
  if (previousIssueKey != null && previousIssueKey.equals(resultObject.getKey())) {
   return;
  }
  FieldDiffs fieldDiffs = FieldDiffs.parse(resultObject.getClosedChangeData()
   .orElseThrow(() -> new IllegalStateException("Close change data should be populated")));
  checkState(Optional.ofNullable(fieldDiffs.get("status"))
   .map(FieldDiffs.Diff::newValue)
   .filter(STATUS_CLOSED::equals)
   .isPresent(), "Close change data should have a status diff with new value %s", STATUS_CLOSED);
  Integer line = Optional.ofNullable(fieldDiffs.get("line"))
   .map(diff -> (String) diff.oldValue())
   .filter(str -> !str.isEmpty())
   .map(Integer::parseInt)
   .orElse(null);
  previousIssueKey = resultObject.getKey();
  DefaultIssue issue = resultObject.toDefaultIssue();
  issue.setLine(line);
  // FIXME
  issue.setSelectedAt(System.currentTimeMillis());
  issues.add(issue);
 }
}
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: shekhargulati/strman-java

/**
 * Removes leading whitespace from string.
 *
 * @param input The string to trim.
 * @return Returns the trimmed string.
 */
public static Optional<String> trimStart(final String input) {
  return Optional.ofNullable(input).filter(v -> !v.isEmpty()).map(Strman::leftTrim);
}
origin: speedment/speedment

.filter(HasEnabled::test)
.filter(col -> col.getTypeMapper()
  .filter(ENUM_TYPE_MAPPERS::contains)
  .isPresent()
).forEachOrdered(col -> {
  final JavaLanguageNamer namer = translator.getSupport().namer();
    throw new UnsupportedOperationException(format(
      "Unknown enum type mapper '%s' in column '%s'.",
      col.getTypeMapper().orElse(null), col
    ));
    EntityTranslatorSupport.getForeignKey(
      translator.getSupport().tableOrThrow(), col
    ).map(fkc -> new FkHolder(injector, fkc.getParentOrThrow()));
  fk.ifPresent(holder -> {
    params.add(ofReference(
      holder.getForeignEmt().getSupport().entityName() + "." +
      .filter(InvocationValue.class::isInstance)
      .map(InvocationValue.class::cast);
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: spring-projects/spring-framework

  Function<A, Boolean> loadContextExtractor, boolean enabledOnTrue, ExtensionContext context) {
Assert.state(context.getElement().isPresent(), "No AnnotatedElement");
AnnotatedElement element = context.getElement().get();
Optional<A> annotation = findMergedAnnotation(element, annotationType);
if (!annotation.isPresent()) {
  String reason = String.format("%s is enabled since @%s is not present", element,
      annotationType.getSimpleName());
String expression = annotation.map(expressionExtractor).map(String::trim).filter(StringUtils::hasLength)
    .orElseThrow(() -> new IllegalStateException(String.format(
        "The expression in @%s on [%s] must not be blank", annotationType.getSimpleName(), element)));
  String reason = annotation.map(reasonExtractor).filter(StringUtils::hasText).orElseGet(
      () -> String.format("%s is %s because @%s(\"%s\") evaluated to true", element, adjective,
        annotationType.getSimpleName(), expression));
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());
  }
}
origin: prestodb/presto

protected void configureGroup(ResourceGroup group, ResourceGroupSpec match)
  if (match.getSoftMemoryLimit().isPresent()) {
    group.setSoftMemoryLimit(match.getSoftMemoryLimit().get());
  group.setSoftConcurrencyLimit(match.getSoftConcurrencyLimit().orElse(match.getHardConcurrencyLimit()));
  group.setHardConcurrencyLimit(match.getHardConcurrencyLimit());
  match.getSchedulingPolicy().ifPresent(group::setSchedulingPolicy);
  match.getSchedulingWeight().ifPresent(group::setSchedulingWeight);
  match.getJmxExport().filter(isEqual(group.getJmxExport()).negate()).ifPresent(group::setJmxExport);
  match.getSoftCpuLimit().ifPresent(group::setSoftCpuLimit);
  match.getHardCpuLimit().ifPresent(group::setHardCpuLimit);
  if (match.getSoftCpuLimit().isPresent() || match.getHardCpuLimit().isPresent()) {
    checkState(getCpuQuotaPeriod().isPresent(), "Must specify hard CPU limit in addition to soft limit");
origin: hs-web/hsweb-framework

@Override
@Transactional(readOnly = true)
public UserEntity selectByUserNameAndPassword(String plainUsername, String plainPassword) {
  Assert.hasLength(plainUsername, "用户名不能为空");
  Assert.hasLength(plainPassword, "密码不能为空");
  return Optional.ofNullable(selectByUsername(plainUsername))
      .filter(user -> encodePassword(plainPassword, user.getSalt()).equals(user.getPassword()))
      .orElse(null);
}
origin: pentaho/pentaho-kettle

 default <T> Optional<T> getConfig( String key, Class<T> type ) {
  return getConfig( key ).filter( type::isInstance ).map( type::cast );
 }
}
origin: speedment/speedment

private boolean checkIf(Document doc, String param, String value) {
  final Pattern pattern = Pattern.compile(value);
  return doc.get(param)
    .map(Object::toString)
    .filter(pattern.asPredicate())
    .isPresent();
}
origin: checkstyle/checkstyle

/**
 * Finds the nearest {@link Suppression} instance which can suppress
 * the given {@link AuditEvent}. The nearest suppression is the suppression which scope
 * is before the line and column of the event.
 * @param suppressions {@link Suppression} instance.
 * @param event {@link AuditEvent} instance.
 * @return {@link Suppression} instance.
 */
private static Suppression getNearestSuppression(List<Suppression> suppressions,
                         AuditEvent event) {
  return suppressions
    .stream()
    .filter(suppression -> suppression.isMatch(event))
    .reduce((first, second) -> second)
    .filter(suppression -> suppression.suppressionType != SuppressionType.ON)
    .orElse(null);
}
origin: apache/flink

  ref.filter(r -> r.has(TYPE)).ifPresent(r -> typeSet.add(convertType(node.get(REF).asText(), r, root)));
else if (ref.isPresent() && ref.get().has(ONE_OF) && ref.get().get(ONE_OF).isArray()) {
  final TypeInformation<?>[] types = convertTypes(node.get(REF).asText() + '/' + ONE_OF, ref.get().get(ONE_OF), root);
  typeSet.addAll(Arrays.asList(types));
origin: ron190/jsql-injection

private void clickArrowButton(String actionKey) {
  JButton scrollForwardButton = null;
  JButton scrollBackwardButton = null;
  for (Component c: this.getComponents()) {
    if (c instanceof JButton) {
      if (scrollForwardButton == null && scrollBackwardButton == null) {
        scrollForwardButton = (JButton) c;
      } else if (scrollBackwardButton == null) {
        scrollBackwardButton = (JButton) c;
      }
    }
  }
  JButton button = "scrollTabsForwardAction".equals(actionKey) ? scrollForwardButton : scrollBackwardButton;
  Optional.ofNullable(button)
    .filter(JButton::isEnabled)
    .ifPresent(JButton::doClick);
}
 
origin: speedment/speedment

      item.getDefaultDbmsName().ifPresent(name -> {
        fieldName.textProperty().setValue(name);
        generatedName.set(name);
    item.getDefaultDbmsName().ifPresent(generatedName::set);
    fieldName.setDisable(true);
      item.getDefaultSchemaName().ifPresent(name -> {
        fieldSchema.textProperty().setValue(name);
        generatedSchema.set(name);
if (preferred.isPresent()) {
  fieldType.getSelectionModel().select(preferred.get());
} else {
    .filter(s -> dbmsType.get().hasDatabaseNames())
    .filter(s -> !s.isEmpty())
    .orElseGet(() -> type.getDefaultDbmsName().orElseGet(fieldName::getText)));
    .filter(s -> dbmsType.get().hasSchemaNames())
    .filter(s -> !s.isEmpty())
    .orElseGet(() -> type.getDefaultSchemaName().orElseGet(dbms::getName));
origin: spring-projects/spring-data-mongodb

  /**
   * Get the string representation.
   *
   * @return
   */
  public String asString() {
    StringBuilder sb = new StringBuilder(language);
    variant.filter(it -> !it.isEmpty()).ifPresent(val -> {
      // Mongo requires variant rendered as ICU keyword (@key=value;key=value…)
      sb.append("@collation=").append(val);
    });
    return sb.toString();
  }
}
java.utilOptionalfilter

Javadoc

If a value is present, and the value matches the given predicate, return an Optional describing the value, otherwise return an empty Optional.

Popular methods of Optional

  • get
  • orElse
  • isPresent
  • ofNullable
  • empty
  • of
  • map
  • ifPresent
  • orElseThrow
  • orElseGet
  • 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
  • From CI to AI: The AI layer in your organization
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