简体   繁体   English

如何转换集合<string>设置<object><div id="text_translate"><p>如何将strRoles转换为Set&lt;Role&gt; 。 先感谢您</p><pre>Set&lt;String&gt; strRoles = signUpRequest.getRoles(); Set&lt;Role&gt; roles = new HashSet&lt;&gt;();</pre><p> <strong>角色.model</strong></p><pre> @Document(collection = "roles") public class Role { @Id private String id; private ERole name; }</pre><p> <strong>Erole.enum</strong></p><pre> public enum ERole { ROLE_ADMIN, ROLE_USER }</pre></div></object></string>

[英]How to convert Set<String> to Set<Object>

How can I convert strRoles to Set<Role> .如何将strRoles转换为Set<Role> Thank you in advance先感谢您

Set<String> strRoles = signUpRequest.getRoles();
Set<Role> roles = new HashSet<>();

Role.model角色.model

@Document(collection = "roles")
public class Role {   
    @Id
    private String id;
    private ERole name;
}

Erole.enum Erole.enum

public enum ERole {
    ROLE_ADMIN,
    ROLE_USER
}

With streams:使用流:

Set<Role> convertStringSetToRoleSetWithStreams(final Set<String> rolesInString) {
    return rolesInString.stream().map(roleInString -> {
        final Role role = new Role();
        role.setName(ERole.valueOf(roleInString));
        return role;
    }).collect(Collectors.toSet());
}

Without streams:没有流:

Set<Role> convertStringSetToRoleSetWithoutStreams(final Set<String> rolesInString) {
    final Set<Role> rolesInObject = new HashSet<>();
    for (final String roleInString : rolesInString) {
        final Role role = new Role();
        role.setName(ERole.valueOf(roleInString));
        rolesInObject.add(role);
    }
    return rolesInObject;
}

Feel free to accept the answer if it works.如果它有效,请随时接受答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM