java.util.Optional.isPresent()方法的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(9.4k)|赞(0)|评价(0)|浏览(152)

本文整理了Java中java.util.Optional.isPresent()方法的一些代码示例,展示了Optional.isPresent()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Optional.isPresent()方法的具体详情如下:
包路径:java.util.Optional
类名称:Optional
方法名:isPresent

Optional.isPresent介绍

[英]Return true if there is a value present, otherwise false.
[中]如果存在值,则返回true,否则返回false。

代码示例

代码示例来源:origin: stackoverflow.com

void foo(String a, Optional<Integer> bOpt) {
  Integer b = bOpt.isPresent() ? bOpt.get() : 0;
  //...
}

foo("a", Optional.of(2));
foo("a", Optional.<Integer>absent());

代码示例来源:origin: prestodb/presto

private static Optional<List<Symbol>> translateSymbols(Iterable<Symbol> partitioning, Function<Symbol, Optional<Symbol>> translator)
{
  ImmutableList.Builder<Symbol> newPartitioningColumns = ImmutableList.builder();
  for (Symbol partitioningColumn : partitioning) {
    Optional<Symbol> translated = translator.apply(partitioningColumn);
    if (!translated.isPresent()) {
      return Optional.empty();
    }
    newPartitioningColumns.add(translated.get());
  }
  return Optional.of(newPartitioningColumns.build());
}

代码示例来源:origin: prestodb/presto

public long getTotalPartitionsCount(String keyspace, String table, Optional<Long> sessionSplitsPerNode)
{
  if (sessionSplitsPerNode.isPresent()) {
    return sessionSplitsPerNode.get();
  }
  else if (configSplitsPerNode.isPresent()) {
    return configSplitsPerNode.get();
  }
  List<SizeEstimate> estimates = session.getSizeEstimates(keyspace, table);
  return estimates.stream()
      .mapToLong(SizeEstimate::getPartitionsCount)
      .sum();
}

代码示例来源: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: prestodb/presto

public List<Symbol> getOriginalNonDistinctAggregateArgs()
{
  return aggregations.values().stream()
      .filter(aggregation -> !aggregation.getMask().isPresent())
      .map(Aggregation::getCall)
      .flatMap(function -> function.getArguments().stream())
      .distinct()
      .map(Symbol::from)
      .collect(Collectors.toList());
}

代码示例来源:origin: prestodb/presto

private static Optional<Domain> getDomain(OptionalInt timestampOrdinalPosition, TupleDomain<LocalFileColumnHandle> predicate)
{
  Optional<Map<LocalFileColumnHandle, Domain>> domains = predicate.getDomains();
  Domain domain = null;
  if (domains.isPresent() && timestampOrdinalPosition.isPresent()) {
    Map<LocalFileColumnHandle, Domain> domainMap = domains.get();
    Set<Domain> timestampDomain = domainMap.entrySet().stream()
        .filter(entry -> entry.getKey().getOrdinalPosition() == timestampOrdinalPosition.getAsInt())
        .map(Map.Entry::getValue)
        .collect(toSet());
    if (!timestampDomain.isEmpty()) {
      domain = Iterables.getOnlyElement(timestampDomain);
    }
  }
  return Optional.ofNullable(domain);
}

代码示例来源:origin: prestodb/presto

public List<SchemaTableName> listTables(Optional<String> schemaName)
{
  return tableDescriptions.getAllSchemaTableNames()
      .stream()
      .filter(schemaTableName -> !schemaName.isPresent() || schemaTableName.getSchemaName().equals(schemaName.get()))
      .collect(toImmutableList());
}

代码示例来源:origin: prestodb/presto

@Override
  public Boolean process(Node node, @Nullable Void context)
  {
    if (expressions.stream().anyMatch(node::equals)
        && (!orderByScope.isPresent() || !hasOrderByReferencesToOutputColumns(node))
        && !hasFreeReferencesToLambdaArgument(node, analysis)) {
      return true;
    }
    return super.process(node, context);
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Test
@SuppressWarnings("rawtypes")
public void missingOptionalParamList() throws Exception {
  ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
  initializer.setConversionService(new DefaultConversionService());
  WebDataBinderFactory binderFactory = new DefaultDataBinderFactory(initializer);
  MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Optional.class, List.class);
  Object result = resolver.resolveArgument(param, null, webRequest, binderFactory);
  assertEquals(Optional.empty(), result);
  result = resolver.resolveArgument(param, null, webRequest, binderFactory);
  assertEquals(Optional.class, result.getClass());
  assertFalse(((Optional) result).isPresent());
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void resolveOptionalParamValue() {
  ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
  MethodParameter param = this.testMethod.arg(forClassWithGenerics(Optional.class, Integer.class));
  Object result = resolve(param, exchange);
  assertEquals(Optional.empty(), result);
  exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path?name=123"));
  result = resolve(param, exchange);
  assertEquals(Optional.class, result.getClass());
  Optional<?> value = (Optional<?>) result;
  assertTrue(value.isPresent());
  assertEquals(123, value.get());
}

代码示例来源:origin: prestodb/presto

private void checkLeftOutputSymbolsBeforeRight(List<Symbol> leftSymbols, List<Symbol> outputSymbols)
{
  int leftMaxPosition = -1;
  Optional<Integer> rightMinPosition = Optional.empty();
  Set<Symbol> leftSymbolsSet = new HashSet<>(leftSymbols);
  for (int i = 0; i < outputSymbols.size(); i++) {
    Symbol symbol = outputSymbols.get(i);
    if (leftSymbolsSet.contains(symbol)) {
      leftMaxPosition = i;
    }
    else if (!rightMinPosition.isPresent()) {
      rightMinPosition = Optional.of(i);
    }
  }
  checkState(!rightMinPosition.isPresent() || rightMinPosition.get() > leftMaxPosition, "Not all left output symbols are before right output symbols");
}

代码示例来源: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: prestodb/presto

@JsonCreator
// Available for Jackson deserialization only!
public static <T> TupleDomain<T> fromColumnDomains(@JsonProperty("columnDomains") Optional<List<ColumnDomain<T>>> columnDomains)
{
  if (!columnDomains.isPresent()) {
    return none();
  }
  return withColumnDomains(columnDomains.get().stream()
      .collect(toMap(ColumnDomain::getColumn, ColumnDomain::getDomain)));
}

代码示例来源:origin: prestodb/presto

public List<Symbol> getOriginalDistinctAggregateArgs()
{
  return aggregations.values().stream()
      .filter(aggregation -> aggregation.getMask().isPresent())
      .map(Aggregation::getCall)
      .flatMap(function -> function.getArguments().stream())
      .distinct()
      .map(Symbol::from)
      .collect(Collectors.toList());
}

代码示例来源:origin: google/guava

/**
 * If a value is present in {@code optional}, returns a stream containing only that element,
 * otherwise returns an empty stream.
 *
 * <p><b>Java 9 users:</b> use {@code optional.stream()} instead.
 */
public static <T> Stream<T> stream(java.util.Optional<T> optional) {
 return optional.isPresent() ? Stream.of(optional.get()) : Stream.of();
}

代码示例来源:origin: prestodb/presto

private Set<NullableValue> filterValues(Set<NullableValue> nullableValues, TpchColumn<?> column, Constraint<ColumnHandle> constraint)
{
  return nullableValues.stream()
      .filter(convertToPredicate(constraint.getSummary(), toColumnHandle(column)))
      .filter(value -> !constraint.predicate().isPresent() || constraint.predicate().get().test(ImmutableMap.of(toColumnHandle(column), value)))
      .collect(toSet());
}

代码示例来源:origin: prestodb/presto

private static boolean isScheduled(Optional<StageInfo> rootStage)
{
  if (!rootStage.isPresent()) {
    return false;
  }
  return getAllStages(rootStage).stream()
      .map(StageInfo::getState)
      .allMatch(state -> (state == StageState.RUNNING) || state.isDone());
}

代码示例来源:origin: spring-projects/spring-framework

@Test
@SuppressWarnings("rawtypes")
public void missingOptionalParamValue() throws Exception {
  ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
  initializer.setConversionService(new DefaultConversionService());
  WebDataBinderFactory binderFactory = new DefaultDataBinderFactory(initializer);
  MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Optional.class, Integer.class);
  Object result = resolver.resolveArgument(param, null, webRequest, binderFactory);
  assertEquals(Optional.empty(), result);
  result = resolver.resolveArgument(param, null, webRequest, binderFactory);
  assertEquals(Optional.class, result.getClass());
  assertFalse(((Optional) result).isPresent());
}

代码示例来源:origin: prestodb/presto

private Optional<Symbol> canonicalize(Optional<Symbol> symbol)
{
  if (symbol.isPresent()) {
    return Optional.of(canonicalize(symbol.get()));
  }
  return Optional.empty();
}

代码示例来源:origin: prestodb/presto

@Override
protected String visitParameter(Parameter node, Void context)
{
  if (parameters.isPresent()) {
    checkArgument(node.getPosition() < parameters.get().size(), "Invalid parameter number %s.  Max value is %s", node.getPosition(), parameters.get().size() - 1);
    return process(parameters.get().get(node.getPosition()), context);
  }
  return "?";
}

相关文章