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

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

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

Optional.of介绍

[英]Returns an Optional with the specified present non-null value.
[中]返回具有指定的当前非空值的可选值。

代码示例

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

public void addMaterializedHandle(TableWriterNode.WriterTarget handle, TableWriterNode.WriterTarget materializedHandle)
{
  checkState(!this.handle.isPresent(), "can only have one WriterTarget in a subtree");
  this.handle = Optional.of(handle);
  this.materializedHandle = Optional.of(materializedHandle);
}

代码示例来源: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: spring-projects/spring-framework

/**
 * Transform the given request into a request used for a nested route. For instance,
 * a path-based predicate can return a {@code ServerRequest} with a the path remaining
 * after a match.
 * <p>The default implementation returns an {@code Optional} wrapping the given path if
 * {@link #test(ServerRequest)} evaluates to {@code true}; or {@link Optional#empty()}
 * if it evaluates to {@code false}.
 * @param request the request to be nested
 * @return the nested request
 * @see RouterFunctions#nest(RequestPredicate, RouterFunction)
 */
default Optional<ServerRequest> nest(ServerRequest request) {
  return (test(request) ? Optional.of(request) : Optional.empty());
}

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

public static Optional<HiveBucketHandle> getHiveBucketHandle(Table table)
{
  Optional<HiveBucketProperty> hiveBucketProperty = table.getStorage().getBucketProperty();
  if (!hiveBucketProperty.isPresent()) {
    return Optional.empty();
  }
  Map<String, HiveColumnHandle> map = getRegularColumnHandles(table).stream()
      .collect(Collectors.toMap(HiveColumnHandle::getName, identity()));
  ImmutableList.Builder<HiveColumnHandle> bucketColumns = ImmutableList.builder();
  for (String bucketColumnName : hiveBucketProperty.get().getBucketedBy()) {
    HiveColumnHandle bucketColumnHandle = map.get(bucketColumnName);
    if (bucketColumnHandle == null) {
      throw new PrestoException(
          HIVE_INVALID_METADATA,
          format("Table '%s.%s' is bucketed on non-existent column '%s'", table.getDatabaseName(), table.getTableName(), bucketColumnName));
    }
    bucketColumns.add(bucketColumnHandle);
  }
  int bucketCount = hiveBucketProperty.get().getBucketCount();
  return Optional.of(new HiveBucketHandle(bucketColumns.build(), bucketCount, bucketCount));
}

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

@Test
public void resolveArgumentWrappedAsOptional() throws Exception {
  Map<String, String> uriTemplateVars = new HashMap<>();
  uriTemplateVars.put("name", "value");
  request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars);
  ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
  initializer.setConversionService(new DefaultConversionService());
  WebDataBinderFactory binderFactory = new DefaultDataBinderFactory(initializer);
  @SuppressWarnings("unchecked")
  Optional<String> result = (Optional<String>)
      resolver.resolveArgument(paramOptional, mavContainer, webRequest, binderFactory);
  assertEquals("PathVariable not resolved correctly", "value", result.get());
  @SuppressWarnings("unchecked")
  Map<String, Object> pathVars = (Map<String, Object>) request.getAttribute(View.PATH_VARIABLES);
  assertNotNull(pathVars);
  assertEquals(1, pathVars.size());
  assertEquals(Optional.of("value"), pathVars.get("name"));
}

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

static <T extends Mergeable<T>> Optional<T> merge(Optional<T> first, Optional<T> second)
  {
    if (first.isPresent() && second.isPresent()) {
      return Optional.of(first.get().mergeWith(second.get()));
    }
    else if (first.isPresent()) {
      return first;
    }

    return second;
  }
}

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

@Override
public ListenableFuture<?> execute(CreateView statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters)
{
  Session session = stateMachine.getSession();
  QualifiedObjectName name = createQualifiedObjectName(session, statement, statement.getName());
  accessControl.checkCanCreateView(session.getRequiredTransactionId(), session.getIdentity(), name);
  String sql = getFormattedSql(statement.getQuery(), sqlParser, Optional.of(parameters));
  Analysis analysis = analyzeStatement(statement, session, metadata, accessControl, parameters, stateMachine.getWarningCollector());
  List<ViewColumn> columns = analysis.getOutputDescriptor(statement.getQuery())
      .getVisibleFields().stream()
      .map(field -> new ViewColumn(field.getName().get(), field.getType()))
      .collect(toImmutableList());
  String data = codec.toJson(new ViewDefinition(sql, session.getCatalog(), session.getSchema(), columns, Optional.of(session.getUser())));
  metadata.createView(session, name, data, statement.isReplace());
  return immediateFuture(null);
}

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

private static LdapObjectDefinition buildLdapGroupObject(String groupName, String userName, Optional<List<String>> childGroupNames)
{
  if (childGroupNames.isPresent()) {
    return buildLdapGroupObject(groupName, AMERICA_DISTINGUISHED_NAME, userName, ASIA_DISTINGUISHED_NAME, childGroupNames, Optional.of(AMERICA_DISTINGUISHED_NAME));
  }
  else {
    return buildLdapGroupObject(groupName, AMERICA_DISTINGUISHED_NAME, userName, ASIA_DISTINGUISHED_NAME,
        Optional.empty(), Optional.empty());
  }
}

代码示例来源:origin: apache/incubator-dubbo

private static Optional<InetAddress> toValidAddress(InetAddress address) {
  if (address instanceof Inet6Address) {
    Inet6Address v6Address = (Inet6Address) address;
    if (isValidV6Address(v6Address)) {
      return Optional.ofNullable(normalizeV6Address(v6Address));
    }
  }
  if (isValidV4Address(address)) {
    return Optional.of(address);
  }
  return Optional.empty();
}

代码示例来源:origin: neo4j/neo4j

@Test
void handlesDeprecationAndReplacement()
{
  ConfigValue value = new ConfigValue( "old_name", Optional.empty(), Optional.empty(), Optional.of( 1 ),
      "description", false, false, true, Optional.of( "new_name" ), false );
  assertEquals( Optional.of( 1 ), value.value() );
  assertEquals( "1", value.toString() );
  assertTrue( value.deprecated() );
  assertEquals( "new_name", value.replacement().get() );
  assertFalse( value.internal() );
  assertFalse( value.secret() );
}

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

public Optional<WithQuery> getNamedQuery(String name)
{
  if (namedQueries.containsKey(name)) {
    return Optional.of(namedQueries.get(name));
  }
  if (parent.isPresent()) {
    return parent.get().getNamedQuery(name);
  }
  return Optional.empty();
}

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

public static <T> Optional<T> combine(Optional<T> left, Optional<T> right, BinaryOperator<T> combiner)
  {
    if (left.isPresent() && right.isPresent()) {
      return Optional.of(combiner.apply(left.get(), right.get()));
    }
    else if (left.isPresent()) {
      return left;
    }
    else {
      return right;
    }
  }
}

代码示例来源:origin: iluwatar/java-design-patterns

/**
 * Can be used to collect objects from the Iterable. Is a terminating operation.
 * 
 * @return an option of the first object of the Iterable
 */
@Override
public final Optional<E> first() {
 Iterator<E> resultIterator = first(1).iterator();
 return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty();
}

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

private static LdapObjectDefinition buildLdapUserObject(String userName, Optional<List<String>> groupNames, String password)
{
  if (groupNames.isPresent()) {
    return buildLdapUserObject(userName, ASIA_DISTINGUISHED_NAME,
        groupNames, Optional.of(AMERICA_DISTINGUISHED_NAME), password);
  }
  else {
    return buildLdapUserObject(userName, ASIA_DISTINGUISHED_NAME,
        Optional.empty(), Optional.empty(), password);
  }
}

代码示例来源:origin: apache/incubator-dubbo

private static Optional<InetAddress> toValidAddress(InetAddress address) {
  if (address instanceof Inet6Address) {
    Inet6Address v6Address = (Inet6Address) address;
    if (isValidV6Address(v6Address)) {
      return Optional.ofNullable(normalizeV6Address(v6Address));
    }
  }
  if (isValidV4Address(address)) {
    return Optional.of(address);
  }
  return Optional.empty();
}

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

public Builder withOuterQueryParent(Scope parent)
{
  checkArgument(!this.parent.isPresent(), "parent is already set");
  this.parent = Optional.of(parent);
  this.queryBoundary = true;
  return this;
}

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

public FragmentProperties setSingleNodeDistribution()
{
  if (partitioningHandle.isPresent() && partitioningHandle.get().isSingleNode()) {
    // already single node distribution
    return this;
  }
  checkState(!partitioningHandle.isPresent(),
      "Cannot overwrite partitioning with %s (currently set to %s)",
      SINGLE_DISTRIBUTION,
      partitioningHandle);
  partitioningHandle = Optional.of(SINGLE_DISTRIBUTION);
  return this;
}

代码示例来源:origin: iluwatar/java-design-patterns

/**
 * Can be used to collect objects from the Iterable. Is a terminating operation.
 * 
 * @return an option of the last object of the Iterable
 */
@Override
public final Optional<E> last() {
 List<E> list = last(1).asList();
 if (list.isEmpty()) {
  return Optional.empty();
 }
 return Optional.of(list.get(0));
}

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

private Optional<Symbol> getAssignedSymbol(Map<Symbol, ColumnHandle> assignments, ColumnHandle columnHandle)
{
  Optional<Symbol> result = Optional.empty();
  for (Map.Entry<Symbol, ColumnHandle> entry : assignments.entrySet()) {
    if (entry.getValue().equals(columnHandle)) {
      checkState(!result.isPresent(), "Multiple ColumnHandles found for %s:%s in table scan assignments", tableName, columnName);
      result = Optional.of(entry.getKey());
    }
  }
  return result;
}

相关文章