本文整理匯總了Java中java.util.Optional.map方法的典型用法代碼示例。如果您正苦於以下問題:Java Optional.map方法的具體用法?Java Optional.map怎麽用?Java Optional.map使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類java.util.Optional
的用法示例。
在下文中一共展示了Optional.map方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: unzip
import java.util.Optional; //導入方法依賴的package包/類
public static void unzip(
final Path source, final Path target, final Optional<String> subPathString, CopyOption... copyOptions) throws IOException {
Preconditions.checkNotNull(source);
Preconditions.checkNotNull(target);
Preconditions.checkNotNull(subPathString);
Preconditions.checkNotNull(copyOptions);
final FileSystem zipFileSystem = zipFileSystem(source);
final Optional<Path> subPath = subPathString.map(x -> zipFileSystem.getPath(zipFileSystem.getSeparator(), x));
Preconditions.checkArgument(!subPath.isPresent() || subPath.get().isAbsolute(), "subPath must be absolute");
final Path sourceInZip = subPath.map(x -> switchFileSystem(zipFileSystem, x))
.orElse(zipFileSystem.getPath(zipFileSystem.getSeparator())).toAbsolutePath();
EvenMoreFiles.copyDirectory(
sourceInZip,
target,
copyOptions);
}
示例2: getProperty
import java.util.Optional; //導入方法依賴的package包/類
/**
* Get the property with given <code>propertyPath</code> from bean property set using the properties full name as
* matching rule.
* @param propertyPath Property path
* @param ignoreMissing <code>true</code> to ignore mismatches
* @return Optional matching bean property
* @throws PropertyNotFoundException If ignoreMissing is false and a matching bean property was not found
*/
private Optional<BeanProperty<?>> getProperty(Path<?> propertyPath, boolean ignoreMissing)
throws PropertyNotFoundException {
ObjectUtils.argumentNotNull(propertyPath, "Property path must be not null");
Optional<PathProperty<?>> beanProperty = stream()
.filter(p -> propertyPath.relativeName().equals(p.relativeName())).findFirst();
if (!ignoreMissing && !beanProperty.isPresent()) {
throw new PropertyNotFoundException((propertyPath instanceof Property) ? (Property<?>) propertyPath : null,
"Property with name [" + propertyPath.relativeName() + "] was not found in bean [" + getBeanClass()
+ "] property set");
}
return beanProperty.map(p -> (BeanProperty<?>) p);
}
示例3: find
import java.util.Optional; //導入方法依賴的package包/類
@Override
public Optional<SingleLookupReply> find(SingleLookupRequest request) {
String endpoint = cfg.getEndpoints().getIdentity().getSingle();
HttpUriRequest req = RestClientUtils.post(endpoint, gson, "lookup",
new LookupSingleRequestJson(request.getType(), request.getThreePid()));
try (CloseableHttpResponse res = client.execute(req)) {
int status = res.getStatusLine().getStatusCode();
if (status < 200 || status >= 300) {
log.warn("REST endpoint {} answered with status {}, no binding found", endpoint, status);
return Optional.empty();
}
Optional<LookupSingleResponseJson> responseOpt = parser.parseOptional(res, "lookup", LookupSingleResponseJson.class);
return responseOpt.map(lookupSingleResponseJson -> new SingleLookupReply(request, getMxId(lookupSingleResponseJson.getId())));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
示例4: findAdministratorEmail
import java.util.Optional; //導入方法依賴的package包/類
private String findAdministratorEmail(Optional<Properties> configFileProperties){
String jvmArgName = JVM_ARG_PREFIX + ADMINISTRATOR_EMAIL;
String jvmArg = System.getProperty(jvmArgName);
if(jvmArg != null){
logJvmArgSource(ADMINISTRATOR_EMAIL, jvmArg, jvmArgName);
return jvmArg;
}
if(configFileProperties.isPresent()){
Optional<String> value = configFileProperties.map(properties -> properties.getProperty(
ADMINISTRATOR_EMAIL));
if(value.isPresent()){
logSource(ADMINISTRATOR_EMAIL, value.get(), configFileLocation);
return value.get();
}
}
logger.error("couldn't find {}", ADMINISTRATOR_EMAIL);
return null;
}
示例5: main
import java.util.Optional; //導入方法依賴的package包/類
public static void main(String[] args) {
String url = "jdbc:h2:mem:test1;DB_CLOSE_DELAY=-1;INIT=runscript from 'src/main/resources/create.sql'";
try {
Connection conn = DriverManager.getConnection(url);
DSLContext create = DSL.using(conn, SQLDialect.H2);
Optional<User> user = create.select(USER.ID, USER.NAME, USER.ADDRESS).from(USER).fetchOptionalInto(User.class);
user.map(u -> {
System.out.println(u);
return null;
});
} catch (SQLException e) {
e.printStackTrace();
}
}
示例6: getStringAttributeValue
import java.util.Optional; //導入方法依賴的package包/類
private static Optional<String> getStringAttributeValue(List<Attribute> attributes, String attributeName) {
final Optional<Attribute> attribute = getAttribute(attributes, attributeName);
return attribute.map(attr -> {
StringValueSamlObject attributeValue = ((StringValueSamlObject) attr.getAttributeValues().get(0));
return Optional.ofNullable(attributeValue.getValue()).orElse("");
});
}
示例7: map
import java.util.Optional; //導入方法依賴的package包/類
@Override
public Optional<Subject> map(final Optional<Object> o) {
/*
* We can not use the the classes directly because they are loaded by a different classloader
* (jetty's CL, not the web app's CL). An the subject is hidden behind two method calls.
*/
return o.map(userIdentity -> (Subject) invokeMethod("getUserIdentity").andThen(invokeMethod("getSubject"))
.apply(userIdentity));
}
示例8: updateUserLogins
import java.util.Optional; //導入方法依賴的package包/類
/**
* Update logins for a specific user, and return the modified user.
*
* @param userKey user key
* @param logins the list of new logins
* @return new user
*/
public Optional<UserDTO> updateUserLogins(String userKey, List<UserLogin> logins) {
Optional<User> f = userRepository
.findOneByUserKey(userKey)
.map(user -> {
List<UserLogin> userLogins = user.getLogins();
userLogins.clear();
logins.forEach(userLogin -> userLogin.setUser(user));
userLogins.addAll(logins);
return user;
});
f.ifPresent(userRepository::save);
return f.map(UserDTO::new);
}
示例9: getEidasMatchingService
import java.util.Optional; //導入方法依賴的package包/類
@Provides
@Singleton
public Optional<EidasMatchingService> getEidasMatchingService(
@Named(COUNTRY_METADATA_RESOLVER) Optional<MetadataResolver> countryMetadataResolver,
@Named(VERIFY_METADATA_RESOLVER) MetadataResolver verifyMetadataResolver,
@Named("VerifyCertificateValidator") CertificateValidator verifyCertificateValidator,
@Named("CountryCertificateValidator") Optional<CertificateValidator> countryCertificateValidator,
X509CertificateFactory x509CertificateFactory,
MatchingServiceAdapterConfiguration configuration,
AssertionDecrypter assertionDecrypter,
UserIdHashFactory userIdHashFactory,
MatchingServiceProxy matchingServiceClient,
MatchingServiceResponseDtoToOutboundResponseFromMatchingServiceMapper responseMapper) {
return countryMetadataResolver.map(countryMetadataResolverValue ->
new EidasMatchingService(
new EidasAttributeQueryValidator(
verifyMetadataResolver,
countryMetadataResolverValue,
verifyCertificateValidator,
countryCertificateValidator.get(),
new CertificateExtractor(),
x509CertificateFactory,
new DateTimeComparator(Duration.ZERO),
assertionDecrypter,
configuration.getCountry().getHubConnectorEntityId()
),
new EidasMatchingRequestToMSRequestTransformer(userIdHashFactory),
matchingServiceClient,
responseMapper));
}
示例10: getDefaultRegionFromConfigFile
import java.util.Optional; //導入方法依賴的package包/類
private Optional<Region> getDefaultRegionFromConfigFile(String profile) {
Optional<String> region = AWSCLIConfigFile.getCredentialProfilesFile()
.flatMap(file -> getRegionFromConfigFile(file, profile));
if (!region.isPresent()) {
region = AWSCLIConfigFile.getConfigFile()
.flatMap(file -> getRegionFromConfigFile(file, profile));
}
return region.map(Region::fromName);
}
示例11: Grant
import java.util.Optional; //導入方法依賴的package包/類
private Grant(Optional<NodeLocation> location, Optional<List<String>> privileges, boolean table, QualifiedName tableName, Identifier grantee, boolean withGrantOption)
{
super(location);
requireNonNull(privileges, "privileges is null");
this.privileges = privileges.map(ImmutableList::copyOf);
this.table = table;
this.tableName = requireNonNull(tableName, "tableName is null");
this.grantee = requireNonNull(grantee, "grantee is null");
this.withGrantOption = withGrantOption;
}
示例12: Revoke
import java.util.Optional; //導入方法依賴的package包/類
private Revoke(Optional<NodeLocation> location, boolean grantOptionFor, Optional<List<String>> privileges, boolean table, QualifiedName tableName, Identifier grantee)
{
super(location);
this.grantOptionFor = grantOptionFor;
requireNonNull(privileges, "privileges is null");
this.privileges = privileges.map(ImmutableList::copyOf);
this.table = table;
this.tableName = requireNonNull(tableName, "tableName is null");
this.grantee = requireNonNull(grantee, "grantee is null");
}
示例13: saveClaim
import java.util.Optional; //導入方法依賴的package包/類
@Transactional
public Claim saveClaim(String submitterId, ClaimData claimData, String authorisation) {
String externalId = claimData.getExternalId().toString();
claimRepository.getClaimByExternalId(externalId).ifPresent(claim -> {
throw new ConflictException("Duplicate claim for external id " + claim.getExternalId());
});
LocalDateTime now = LocalDateTimeFactory.nowInLocalZone();
Optional<GeneratePinResponse> pinResponse = Optional.empty();
if (!claimData.isClaimantRepresented()) {
pinResponse = Optional.of(userService.generatePin(claimData.getDefendant().getName(), authorisation));
}
Optional<String> letterHolderId = pinResponse.map(GeneratePinResponse::getUserId);
LocalDate issuedOn = issueDateCalculator.calculateIssueDay(now);
LocalDate responseDeadline = responseDeadlineCalculator.calculateResponseDeadline(issuedOn);
UserDetails userDetails = userService.getUserDetails(authorisation);
String submitterEmail = userDetails.getEmail();
String claimDataString = jsonMapper.toJson(claimData);
long issuedClaimId;
if (claimData.isClaimantRepresented()) {
issuedClaimId = claimRepository.saveRepresented(claimDataString, submitterId, issuedOn,
responseDeadline, externalId, submitterEmail);
} else {
issuedClaimId = claimRepository.saveSubmittedByClaimant(claimDataString, submitterId,
letterHolderId.orElseThrow(IllegalStateException::new), issuedOn, responseDeadline,
externalId, submitterEmail);
}
eventProducer.createClaimIssuedEvent(
getClaimById(issuedClaimId),
pinResponse.map(GeneratePinResponse::getPin).orElse(null),
userDetails.getFullName(),
authorisation
);
return getClaimById(issuedClaimId);
}
示例14: asString
import java.util.Optional; //導入方法依賴的package包/類
private Optional<String> asString(final Optional<SecretEntry> secretEntry) {
verifyEncodingOrThrow(secretEntry, Encoding.UTF8);
return secretEntry.map(e -> e.secretValue.asString());
}
示例15: getLabel
import java.util.Optional; //導入方法依賴的package包/類
private Optional<RelationMember> getLabel(GeometrySerializer serializer, Map<String, String> tags, MultiPolygon multiPolygon) {
Optional<Node> labelNode = serializer.writePoint(GEOMETRY_FACTORY.createPoint(getCentroid(multiPolygon)), tags);
return labelNode.map(node -> new RelationMember(node.getId(), Node, "label"));
}