本文整理了Java中java.util.Optional.ofNullable()
方法的一些代码示例,展示了Optional.ofNullable()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Optional.ofNullable()
方法的具体详情如下:
包路径:java.util.Optional
类名称:Optional
方法名:ofNullable
[英]Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.
[中]返回描述指定值的可选值,如果为非null,则返回空可选值。
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: iluwatar/java-design-patterns
@Override
public Optional<Customer> getById(final int id) {
return Optional.ofNullable(idToCustomer.get(id));
}
代码示例来源: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: dropwizard/dropwizard
@Override
@JsonProperty
public Optional<Duration> getValidationQueryTimeout() {
return Optional.ofNullable(validationQueryTimeout);
}
代码示例来源:origin: dropwizard/dropwizard
@Override
public void configure(Map<String, String> options) {
useCache = Optional.ofNullable(options.get("cache")).map(Boolean::parseBoolean).orElse(true);
fileRoot = Optional.ofNullable(options.get("fileRoot")).map(File::new);
}
代码示例来源:origin: Netflix/eureka
/**
* Gets the list of <em>instances</em> associated to a virtual host name.
*
* @param virtualHostName
* the virtual hostname for which the instances need to be
* returned.
* @return list of <em>instances</em>.
*/
public List<InstanceInfo> getInstancesByVirtualHostName(String virtualHostName) {
return Optional.ofNullable(this.virtualHostNameAppMap.get(virtualHostName.toUpperCase(Locale.ROOT)))
.map(VipIndexSupport::getVipList)
.map(AtomicReference::get)
.orElseGet(Collections::emptyList);
}
代码示例来源:origin: gocd/gocd
private Optional<String> parseTag(ProcessType requestType, LogLevel logLevel) {
switch (requestType) {
case FETCH:
return Optional.ofNullable(FETCH_ARTIFACT_LOG_LEVEL_TAG.get(logLevel));
case PUBLISH:
return Optional.ofNullable(PUBLISH_ARTIFACT_LOG_LEVEL_TAG.get(logLevel));
}
return Optional.empty();
}
代码示例来源:origin: hs-web/hsweb-framework
public Optional<String> getStringConfig(String name) {
return config == null ?
Optional.empty() :
Optional.ofNullable(config.get(name))
.map(String::valueOf);
}
}
代码示例来源:origin: apache/kafka
Optional<PartitionInfo> getPartitionInfo(TopicPartition topicPartition) {
return Optional.ofNullable(metadataByPartition.get(topicPartition))
.map(PartitionInfoAndEpoch::partitionInfo);
}
代码示例来源:origin: prestodb/presto
public List<GroupingOperation> getGroupingOperations(QuerySpecification querySpecification)
{
return Optional.ofNullable(groupingOperations.get(NodeRef.of(querySpecification)))
.orElse(emptyList());
}
代码示例来源: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: apache/flink
public <R> Optional<R> map(Function<? super T, ? extends R> mapper) {
if (value == null) {
return Optional.empty();
} else {
return Optional.ofNullable(mapper.apply(value));
}
}
代码示例来源:origin: prestodb/presto
@Override
public OptionalDouble getValueFromAggregationQueryResult(Object value)
{
return Optional.ofNullable(value)
.map(Number.class::cast)
.map(Number::doubleValue)
.map(OptionalDouble::of)
.orElseGet(OptionalDouble::empty);
}
代码示例来源:origin: spring-projects/spring-framework
private static <T, S extends Publisher<T>> S readWithMessageReaders(
ReactiveHttpInputMessage message, BodyExtractor.Context context, ResolvableType elementType,
Function<HttpMessageReader<T>, S> readerFunction,
Function<UnsupportedMediaTypeException, S> errorFunction,
Supplier<S> emptySupplier) {
if (VOID_TYPE.equals(elementType)) {
return emptySupplier.get();
}
MediaType contentType = Optional.ofNullable(message.getHeaders().getContentType())
.orElse(MediaType.APPLICATION_OCTET_STREAM);
return context.messageReaders().stream()
.filter(reader -> reader.canRead(elementType, contentType))
.findFirst()
.map(BodyExtractors::<T>cast)
.map(readerFunction)
.orElseGet(() -> {
List<MediaType> mediaTypes = context.messageReaders().stream()
.flatMap(reader -> reader.getReadableMediaTypes().stream())
.collect(Collectors.toList());
return errorFunction.apply(
new UnsupportedMediaTypeException(contentType, mediaTypes, elementType));
});
}
代码示例来源:origin: prestodb/presto
private Optional<QueryFailureInfo> createQueryFailureInfo(ExecutionFailureInfo failureInfo, Optional<StageInfo> outputStage)
{
if (failureInfo == null) {
return Optional.empty();
}
Optional<TaskInfo> failedTask = outputStage.flatMap(QueryMonitor::findFailedTask);
return Optional.of(new QueryFailureInfo(
failureInfo.getErrorCode(),
Optional.ofNullable(failureInfo.getType()),
Optional.ofNullable(failureInfo.getMessage()),
failedTask.map(task -> task.getTaskStatus().getTaskId().toString()),
failedTask.map(task -> task.getTaskStatus().getSelf().getHost()),
executionFailureInfoCodec.toJson(failureInfo)));
}
代码示例来源: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: perwendel/spark
public static String fromResource(AbstractFileResolvingResource resource) {
String filename = Optional.ofNullable(resource.getFilename()).orElse("");
return getMimeType(filename);
}
代码示例来源:origin: SonarSource/sonarqube
private RuleUpdate createRuleUpdate(DbSession dbSession, RuleKey key, OrganizationDto organization) {
RuleDto rule = dbClient.ruleDao().selectByKey(dbSession, organization, key)
.orElseThrow(() -> new NotFoundException(format("This rule does not exist: %s", key)));
RuleUpdate ruleUpdate = ofNullable(rule.getTemplateId())
.map(x -> RuleUpdate.createForCustomRule(key))
.orElseGet(() -> RuleUpdate.createForPluginRule(key));
ruleUpdate.setOrganization(organization);
return ruleUpdate;
}
代码示例来源:origin: Netflix/eureka
/**
* Gets the list of instances associated with this particular application.
* <p>
* Note that the instances are always returned with random order after
* shuffling to avoid traffic to the same instances during startup. The
* shuffling always happens once after every fetch cycle as specified in
* {@link EurekaClientConfig#getRegistryFetchIntervalSeconds}.
* </p>
*
* @return the list of shuffled instances associated with this application.
*/
@JsonProperty("instance")
public List<InstanceInfo> getInstances() {
return Optional.ofNullable(shuffledInstances.get()).orElseGet(this::getInstancesAsIsFromEureka);
}
代码示例来源: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());
}
}
内容来源于网络,如有侵权,请联系作者删除!