本文整理了Java中java.util.Optional.ifPresent()
方法的一些代码示例,展示了Optional.ifPresent()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Optional.ifPresent()
方法的具体详情如下:
包路径:java.util.Optional
类名称:Optional
方法名:ifPresent
[英]If a value is present, invoke the specified consumer with the value, otherwise do nothing.
[中]如果存在值,则使用该值调用指定的使用者,否则不执行任何操作。
代码示例来源:origin: prestodb/presto
@Override
public List<Node> getChildren()
{
ImmutableList.Builder<Node> nodes = ImmutableList.builder();
window.ifPresent(nodes::add);
filter.ifPresent(nodes::add);
orderBy.map(OrderBy::getSortItems).map(nodes::addAll);
nodes.addAll(arguments);
return nodes.build();
}
代码示例来源:origin: prestodb/presto
public void rollback()
{
Optional.ofNullable(rollbackAction.getAndSet(null)).ifPresent(Runnable::run);
}
代码示例来源:origin: neo4j/neo4j
public void forEach( BiConsumer<String,URI> consumer )
{
entries.stream().collect( Collectors.groupingBy( e -> e.key ) )
.forEach( ( key, list ) -> list.stream()
.max( Comparator.comparing( e -> e.precedence ) )
.ifPresent( e -> consumer.accept( key, e.uri ) ) );
}
代码示例来源:origin: ethereum/ethereumj
public DefaultConfig() {
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
logger.error("Uncaught exception", e);
FATAL_EXCEPTIONS.stream()
.filter(errType -> errType.isInstance(e))
.findFirst()
.ifPresent(errType -> System.exit(1));
});
}
代码示例来源:origin: prestodb/presto
private void validateSelectors(List<ResourceGroupSpec> groups, SelectorSpec spec)
{
spec.getQueryType().ifPresent(this::validateQueryType);
List<ResourceGroupNameTemplate> selectorGroups = spec.getGroup().getSegments();
StringBuilder fullyQualifiedGroupName = new StringBuilder();
while (!selectorGroups.isEmpty()) {
ResourceGroupNameTemplate groupName = selectorGroups.get(0);
fullyQualifiedGroupName.append(groupName);
Optional<ResourceGroupSpec> match = groups
.stream()
.filter(groupSpec -> groupSpec.getName().equals(groupName))
.findFirst();
if (!match.isPresent()) {
throw new IllegalArgumentException(format("Selector refers to nonexistent group: %s", fullyQualifiedGroupName.toString()));
}
fullyQualifiedGroupName.append(".");
groups = match.get().getSubGroups();
selectorGroups = selectorGroups.subList(1, selectorGroups.size());
}
}
代码示例来源: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: jenkinsci/jenkins
/**
* Returns initial {@link Method} as well as all matching ones found in interfaces.
* This allows to introspect metadata for a method which is both declared in parent class and in implemented
* interface(s). <code>interfaces</code> typically is obtained by {@link ClassUtils#getAllInterfacesAsSet}
*/
Collection<Method> getMethodAndInterfaceDeclarations(Method method, Collection<Class> interfaces) {
final List<Method> methods = new ArrayList<>();
methods.add(method);
// we search for matching method by iteration and comparison vs getMethod to avoid repeated NoSuchMethodException
// being thrown, while interface typically only define a few set of methods to check.
interfaces.stream()
.map(Class::getMethods)
.flatMap(Arrays::stream)
.filter(m -> m.getName().equals(method.getName()) && Arrays.equals(m.getParameterTypes(), method.getParameterTypes()))
.findFirst()
.ifPresent(methods::add);
return methods;
}
代码示例来源:origin: prestodb/presto
public String getBearerToken(String subject)
{
checkState(jwtSigner.isPresent(), "not configured");
JwtBuilder jwt = Jwts.builder()
.setSubject(subject)
.setExpiration(Date.from(ZonedDateTime.now().plusMinutes(5).toInstant()));
jwtSigner.get().accept(jwt);
jwtKeyId.ifPresent(keyId -> jwt.setHeaderParam(KEY_ID, keyId));
jwtIssuer.ifPresent(jwt::setIssuer);
jwtAudience.ifPresent(jwt::setAudience);
return jwt.compact();
}
代码示例来源:origin: SonarSource/sonarqube
private static void addPullRequest(ProjectPullRequests.ListWsResponse.Builder response, BranchDto branch, Map<String, BranchDto> mergeBranchesByUuid,
@Nullable LiveMeasureDto qualityGateMeasure, BranchStatistics branchStatistics, @Nullable String analysisDate) {
Optional<BranchDto> mergeBranch = Optional.ofNullable(mergeBranchesByUuid.get(branch.getMergeBranchUuid()));
ProjectPullRequests.PullRequest.Builder builder = ProjectPullRequests.PullRequest.newBuilder();
builder.setKey(branch.getKey());
DbProjectBranches.PullRequestData pullRequestData = requireNonNull(branch.getPullRequestData(), "Pull request data should be available for branch type PULL_REQUEST");
builder.setBranch(pullRequestData.getBranch());
ofNullable(emptyToNull(pullRequestData.getUrl())).ifPresent(builder::setUrl);
ofNullable(emptyToNull(pullRequestData.getTitle())).ifPresent(builder::setTitle);
if (mergeBranch.isPresent()) {
String mergeBranchKey = mergeBranch.get().getKey();
builder.setBase(mergeBranchKey);
} else {
builder.setIsOrphan(true);
}
ofNullable(analysisDate).ifPresent(builder::setAnalysisDate);
setQualityGate(builder, qualityGateMeasure, branchStatistics);
response.addPullRequests(builder);
}
代码示例来源:origin: prestodb/presto
private static void addAllStages(Optional<StageInfo> stageInfo, ImmutableList.Builder<StageInfo> collector)
{
stageInfo.ifPresent(stage -> {
collector.add(stage);
stage.getSubStages().stream()
.forEach(subStage -> addAllStages(Optional.ofNullable(subStage), collector));
});
}
代码示例来源:origin: prestodb/presto
private void analyzeHaving(QuerySpecification node, Scope scope)
{
if (node.getHaving().isPresent()) {
Expression predicate = node.getHaving().get();
ExpressionAnalysis expressionAnalysis = analyzeExpression(predicate, scope);
expressionAnalysis.getWindowFunctions().stream()
.findFirst()
.ifPresent(function -> {
throw new SemanticException(NESTED_WINDOW, function.getNode(), "HAVING clause cannot contain window functions");
});
analysis.recordSubqueries(node, expressionAnalysis);
Type predicateType = expressionAnalysis.getType(predicate);
if (!predicateType.equals(BOOLEAN) && !predicateType.equals(UNKNOWN)) {
throw new SemanticException(TYPE_MISMATCH, predicate, "HAVING clause must evaluate to a boolean: actual type %s", predicateType);
}
analysis.setHaving(node, predicate);
}
}
代码示例来源:origin: prestodb/presto
private void flattenNode(PlanNode node, int limit)
{
PlanNode resolved = lookup.resolve(node);
// (limit - 2) because you need to account for adding left and right side
if (!(resolved instanceof JoinNode) || (sources.size() > (limit - 2))) {
sources.add(node);
return;
}
JoinNode joinNode = (JoinNode) resolved;
if (joinNode.getType() != INNER || !isDeterministic(joinNode.getFilter().orElse(TRUE_LITERAL)) || joinNode.getDistributionType().isPresent()) {
sources.add(node);
return;
}
// we set the left limit to limit - 1 to account for the node on the right
flattenNode(joinNode.getLeft(), limit - 1);
flattenNode(joinNode.getRight(), limit);
joinNode.getCriteria().stream()
.map(EquiJoinClause::toExpression)
.forEach(filters::add);
joinNode.getFilter().ifPresent(filters::add);
}
代码示例来源:origin: prestodb/presto
public static void checkTableName(String catalogName, Optional<String> schemaName, Optional<String> tableName)
{
checkCatalogName(catalogName);
schemaName.ifPresent(name -> checkLowerCase(name, "schemaName"));
tableName.ifPresent(name -> checkLowerCase(name, "tableName"));
checkArgument(schemaName.isPresent() || !tableName.isPresent(), "tableName specified but schemaName is missing");
}
代码示例来源:origin: SonarSource/sonarqube
private static void writeIfNeeded(String fieldName, @Nullable Date value, Consumer<String> setter, Set<String> desiredFields) {
if (desiredFields.contains(fieldName)) {
ofNullable(value).map(DateUtils::formatDateTime).ifPresent(setter);
}
}
代码示例来源:origin: rest-assured/rest-assured
private Object[] resolvePathParams(Object[] pathParams) {
Arrays.stream(pathParams).filter(param -> !(param instanceof String))
.findAny().ifPresent(param -> {
throw new IllegalArgumentException("Only Strings allowed in path parameters.");
});
return Arrays.stream(pathParams)
.map(param -> UriUtils.encode((String) param, Charsets.UTF_8)).toArray();
}
代码示例来源:origin: spring-projects/spring-framework
/**
* Checks whether all of the data buffers allocated by this factory have also been released.
* If not, then an {@link AssertionError} is thrown. Typically used from a JUnit {@link After}
* method.
*/
public void checkForLeaks() {
this.created.stream()
.filter(LeakAwareDataBuffer::isAllocated)
.findFirst()
.map(LeakAwareDataBuffer::leakError)
.ifPresent(leakError -> {
throw leakError;
});
}
代码示例来源:origin: SonarSource/sonarqube
private List<Setting> loadSettings(DbSession dbSession, Optional<ComponentDto> component, Set<String> keys) {
// List of settings must be kept in the following orders : default -> global -> component -> branch
List<Setting> settings = new ArrayList<>();
settings.addAll(loadDefaultValues(keys));
settings.addAll(loadGlobalSettings(dbSession, keys));
if (component.isPresent() && component.get().getBranch() != null && component.get().getMainBranchProjectUuid() != null) {
ComponentDto project = dbClient.componentDao().selectOrFailByUuid(dbSession, component.get().getMainBranchProjectUuid());
settings.addAll(loadComponentSettings(dbSession, keys, project).values());
}
component.ifPresent(componentDto -> settings.addAll(loadComponentSettings(dbSession, keys, componentDto).values()));
return settings.stream()
.filter(s -> settingsWsSupport.isVisible(s.getKey(), s.getDefinition(), component))
.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: apache/flink
/**
* Validates that the given prefix is not included in these properties.
*/
public void validatePrefixExclusion(String prefix) {
properties.keySet().stream()
.filter(k -> k.startsWith(prefix))
.findFirst()
.ifPresent((k) -> {
throw new ValidationException(
"Properties with prefix '" + prefix + "' are not allowed in this context. " +
"But property '" + k + "' was found.");
});
}
代码示例来源:origin: SonarSource/sonarqube
private List<String> getValues() {
Optional<String> value = readParam("value");
if (!value.isPresent()) {
List<String> values = new ArrayList<>();
readBody().ifPresent(values::add);
return values;
}
return VALUE_SPLITTER.splitToList(value.get());
}
内容来源于网络,如有侵权,请联系作者删除!