本文整理了Java中java.util.Optional
类的一些代码示例,展示了Optional
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Optional
类的具体详情如下:
包路径:java.util.Optional
类名称:Optional
[英]A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.
Additional methods that depend on the presence or absence of a contained value are provided, such as #orElse(java.lang.Object)(return a default value if value not present) and #ifPresent(java.util.function.Consumer) (execute a block of code if the value is present).
This is a value-based class; use of identity-sensitive operations (including reference equality ( ==), identity hash code, or synchronization) on instances of Optional may have unpredictable results and should be avoided.
[中]可以包含或不包含非空值的容器对象。如果存在值,isPresent()将返回true,get()将返回该值。
提供了依赖于包含值的存在与否的其他方法,例如#orElse(java.lang.Object)(如果值不存在,则返回默认值)和#ifPresent(java.util.function.Consumer)(如果值存在,则执行代码块)。
这是一个{$0$}类;在Optional实例上使用标识敏感操作(包括引用相等(=)、标识哈希代码或同步)可能会产生不可预测的结果,应避免。
canonical example by Tabnine
private Double calculateAverageGrade(Map<String, List<Integer>> gradesList, String studentName)
throws Exception {
return Optional.ofNullable(gradesList.get(studentName))
.map(list -> list.stream().collect(Collectors.averagingDouble(x -> x)))
.orElseThrow(() -> new Exception("Student not found - " + studentName));
}
代码示例来源:origin: prestodb/presto
public boolean hasAllOutputs(TableScanNode node)
{
if (!layout.getColumns().isPresent()) {
return true;
}
Set<ColumnHandle> columns = ImmutableSet.copyOf(layout.getColumns().get());
List<ColumnHandle> nodeColumnHandles = node.getOutputSymbols().stream()
.map(node.getAssignments()::get)
.collect(toImmutableList());
return columns.containsAll(nodeColumnHandles);
}
代码示例来源:origin: spring-projects/spring-framework
@Override
@Nullable
public CorsConfiguration getCorsConfiguration(ServerWebExchange exchange) {
PathContainer lookupPath = exchange.getRequest().getPath().pathWithinApplication();
return this.corsConfigurations.entrySet().stream()
.filter(entry -> entry.getKey().matches(lookupPath))
.map(Map.Entry::getValue)
.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: 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: spring-projects/spring-framework
/**
* Determine a media type for the given resource, if possible.
* @param resource the resource to introspect
* @return the corresponding media type, or {@code null} if none found
*/
public static Optional<MediaType> getMediaType(@Nullable Resource resource) {
return Optional.ofNullable(resource)
.map(Resource::getFilename)
.flatMap(MediaTypeFactory::getMediaType);
}
代码示例来源: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: prestodb/presto
@Override
public synchronized Optional<List<String>> getPartitionNames(String databaseName, String tableName)
{
return Optional.of(ImmutableList.copyOf(partitions.entrySet().stream()
.filter(entry -> entry.getKey().matches(databaseName, tableName))
.map(entry -> entry.getKey().getPartitionName())
.collect(toList())));
}
代码示例来源: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: 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
private synchronized Collection<HivePrivilegeInfo> getTablePrivileges(
Path permissionsDirectory,
String principalName,
PrincipalType principalType)
{
Path permissionFilePath = getPermissionsPath(permissionsDirectory, principalName, principalType);
return readFile("permissions", permissionFilePath, permissionsCodec).orElse(ImmutableList.of()).stream()
.map(PermissionMetadata::toHivePrivilegeInfo)
.collect(toList());
}
代码示例来源:origin: prestodb/presto
@VisibleForTesting
public Supplier<PageProcessor> createPageProcessor(Page filterTuple, OptionalInt initialBatchSize)
{
TuplePageFilter filter = new TuplePageFilter(filterTuple, filterTypes, outputFilterChannels);
return () -> new PageProcessor(
Optional.of(filter),
outputProjections.stream()
.map(Supplier::get)
.collect(toImmutableList()), initialBatchSize);
}
代码示例来源: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
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
private static TypeSignature makeSignature(List<Field> fields)
{
int size = fields.size();
if (size == 0) {
throw new IllegalArgumentException("Row type must have at least 1 field");
}
List<TypeSignatureParameter> parameters = fields.stream()
.map(field -> TypeSignatureParameter.of(new NamedTypeSignature(field.getName().map(name -> new RowFieldName(name, false)), field.getType().getTypeSignature())))
.collect(Collectors.toList());
return new TypeSignature(ROW, parameters);
}
代码示例来源: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 Expression toPredicate(TupleDomain<Symbol> tupleDomain)
{
if (tupleDomain.isNone()) {
return FALSE_LITERAL;
}
Map<Symbol, Domain> domains = tupleDomain.getDomains().get();
return domains.entrySet().stream()
.sorted(comparing(entry -> entry.getKey().getName()))
.map(entry -> toPredicate(entry.getValue(), entry.getKey().toSymbolReference()))
.collect(collectingAndThen(toImmutableList(), ExpressionUtils::combineConjuncts));
}
代码示例来源:origin: prestodb/presto
private String getPartitionName(String databaseName, String tableName, List<String> partitionValues)
{
Table table = getTable(databaseName, tableName)
.orElseThrow(() -> new TableNotFoundException(new SchemaTableName(databaseName, tableName)));
List<String> columnNames = table.getPartitionColumns().stream()
.map(Column::getName)
.collect(toImmutableList());
return makePartName(columnNames, partitionValues);
}
代码示例来源:origin: prestodb/presto
private static PlanFragment createUnionPlanFragment(String name, PlanFragment... fragments)
{
PlanNode planNode = new UnionNode(
new PlanNodeId(name + "_id"),
Stream.of(fragments)
.map(fragment -> new RemoteSourceNode(new PlanNodeId(fragment.getId().toString()), fragment.getId(), fragment.getPartitioningScheme().getOutputLayout(), Optional.empty(), REPARTITION))
.collect(toImmutableList()),
ImmutableListMultimap.of(),
ImmutableList.of());
return createFragment(planNode);
}
代码示例来源:origin: spring-projects/spring-framework
@ParameterizedTest
@ValueSource(strings = { "Dilbert", "Wally" })
void people(String name, @Autowired List<Person> people) {
assertTrue(people.stream().map(Person::getName).filter(str -> name.equals(str)).findFirst().isPresent());
}
内容来源于网络,如有侵权,请联系作者删除!