当前位置: 首页>>代码示例>>Java>>正文


Java Optional.map方法代码示例

本文整理汇总了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);
}
 
开发者ID:LoopPerfect,项目名称:buckaroo,代码行数:23,代码来源:EvenMoreFiles.java

示例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);
}
 
开发者ID:holon-platform,项目名称:holon-core,代码行数:21,代码来源:DefaultBeanPropertySet.java

示例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);
    }
}
 
开发者ID:kamax-io,项目名称:mxisd,代码行数:20,代码来源:RestThreePidProvider.java

示例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;
}
 
开发者ID:hotpads,项目名称:datarouter,代码行数:19,代码来源:DatarouterProperties.java

示例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();
		}

	}
 
开发者ID:vrcod,项目名称:slick-jooq,代码行数:17,代码来源:Main.java

示例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("");
    });
}
 
开发者ID:alphagov,项目名称:verify-service-provider,代码行数:8,代码来源:AttributeTranslationService.java

示例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));
}
 
开发者ID:gmuecke,项目名称:boutique-de-jus,代码行数:11,代码来源:JettySupport.java

示例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);
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:21,代码来源:UserService.java

示例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));
}
 
开发者ID:alphagov,项目名称:verify-matching-service-adapter,代码行数:32,代码来源:MatchingServiceAdapterModule.java

示例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);
    }
 
开发者ID:schibsted,项目名称:strongbox,代码行数:13,代码来源:CustomRegionProviderChain.java

示例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;
}
 
开发者ID:dbiir,项目名称:rainbow,代码行数:11,代码来源:Grant.java

示例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");
}
 
开发者ID:dbiir,项目名称:rainbow,代码行数:11,代码来源:Revoke.java

示例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);
}
 
开发者ID:hmcts,项目名称:cmc-claim-store,代码行数:44,代码来源:ClaimService.java

示例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());
}
 
开发者ID:schibsted,项目名称:strongbox,代码行数:5,代码来源:DefaultSimpleSecretsGroup.java

示例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"));
}
 
开发者ID:Mappy,项目名称:fpm,代码行数:5,代码来源:BuiltUpShapefile.java


注:本文中的java.util.Optional.map方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。