如何将字符串列表转换为对象列表?

时间:2017-11-06 18:15:24

标签: java java-8 stream java-stream

我有一个数据库中的角色列表。它们的形式为

application.Role1.read
application.Role1.write
application.Role2.read
application.Role3.read

因此每个角色都有一个基于读/写权限的条目。 我想将角色转换为POJO,然后我可以将其作为JSON发送到UI。每个POJO都有角色名称,以及读取或写入权限的布尔值。

这是RolePermission类:

import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class RolePermission {
    private String roleName;
    private boolean readAllowed;
    private boolean writeAllowed;

    public String getRoleName() {
        return roleName;
    }

    public RolePermission setRoleName(String roleName) {
        this.roleName = roleName;
        return this;
    }

    public boolean isReadAllowed() {
        return readAllowed;
    }

    public RolePermission setReadAllowed(boolean readAllowed) {
        this.readAllowed = readAllowed;
        return this;
    }

    public boolean isWriteAllowed() {
        return writeAllowed;
    }

    public RolePermission setWriteAllowed(boolean writeAllowed) {
        this.writeAllowed = writeAllowed;
        return this;
    }
}

我正在做这样的转变:

public static final String ROLE_PREFIX = "application.";
public static final String ROLE_READ_PERMISSION = "read";
public static final String ROLE_WRITE_PERMISSION = "write";

@Override
public List<RolePermission> getRoles(Backend backend) {
    List<String> allRoles = backend.getRoles()
            .stream()
            .map(s -> s.replace(ROLE_PREFIX, ""))
            .sorted()
            .collect(Collectors.toList());
    Map<String, RolePermission> roleMap = new HashMap<>();
    for (String role : allRoles) {
        String[] tokens = role.split(".");
        String roleName = tokens[0];
        String permission = tokens[1];
        if (!roleMap.containsKey(roleName))
            roleMap.put(roleName, new RolePermission().setRoleName(roleName));
        RolePermission permission = roleMap.get(roleName);
        if (ROLE_READ_PERMISSION.equals(permission))
            permission.setReadAllowed(true);
        if (ROLE_WRITE_PERMISSION.equals(permission))
            permission.setWriteAllowed(true);
    }
    return new LinkedList<>(roleMap.values());
}

有没有办法使用Java 8流进行上面的foreach循环?

这是一个模拟后端实例,只返回一个角色列表:

public class Backend {
    public List<String> getRoles() {
        return Arrays.asList(
            "application.Role1.read",
            "application.Role1.write",
            "application.Role2.read",
            "application.Role3.read"
        );
    }
}

3 个答案:

答案 0 :(得分:4)

您可以使用groupingBy一起加入同一个roleName的不同权限。

public static final String ROLE_PREFIX = "application.";
public static final String ROLE_READ_PERMISSION = "read";
public static final String ROLE_WRITE_PERMISSION = "write";

@Override
public List<RolePermission> getRoles(Backend backend) {
    Map<String, List<String[]>> allRoles = backend.getRoles()
            .stream()
            .map(s -> s.replace(ROLE_PREFIX, "")) // something like "Role1.read"
            .map(s -> s.split("\\.")) // something like ["Role1", "read"]
            .collect(Collectors.groupingBy(split -> split[0]));
    return allRoles.values()
                   .stream()
                   .map(this::buildPermission)
                   .collect(Collectors.toList());
}

private RolePermission buildPermission(List<String[]> roleEntries) {
    RolePermission permission = new RolePermission().setRoleName(roleEntries.get(0)[0]);
    roleEntries.stream()
               .forEach(entry -> {
                   if (ROLE_READ_PERMISSION.equals(entry[1]))
                       permission.setReadAllowed(true);
                   if (ROLE_WRITE_PERMISSION.equals(entry[1]))
                       permission.setWriteAllowed(true);
               });
    return permission;
}

我还认为您的String.split在原始帖子中使用了错误的正则表达式,因为.special regex character。我已对此进行了测试,并且工作正常。

输出:

[RolePermission(roleName=Role3, readAllowed=true, writeAllowed=false), 
 RolePermission(roleName=Role2, readAllowed=true, writeAllowed=false),
 RolePermission(roleName=Role1, readAllowed=true, writeAllowed=true)]

答案 1 :(得分:0)

您的for循环可以替换为现有流和map收集器中toMap的第二次呼叫:

public List<RolePermission> getRoles(Backend backend)
{
    Map<String, RolePermission> allRoles = backend.getRoles()
            .stream()
            .map(s -> s.replace(ROLE_PREFIX, ""))
            .sorted()
            .map(this::mapStringToRolePermission)
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, RolePermission::merge));
    return new ArrayList<>(allRoles.values());
}

其中mapStringToRolePermission

private static Map.Entry<String, RolePermission> mapStringToRolePermission(String role)
{
    String roleName = role.substring(0, role.indexOf('.'));
    RolePermission rolePermission = new RolePermission();
    rolePermission.setRoleName(roleName);
    rolePermission.setReadAllowed(role.endsWith(ROLE_READ_PERMISSION));
    rolePermission.setWriteAllowed(role.endsWith(ROLE_WRITE_PERMISSION));
    return new AbstractMap.SimpleEntry<>(roleName, rolePermission);
}

以及merge的其他方法RolePermission

public RolePermission merge(RolePermission another)
{
    if (another.isReadAllowed())
        setReadAllowed(true);
    if (another.isWriteAllowed())
        setWriteAllowed(true);
    return this;
}

答案 2 :(得分:-1)

Java流具有map函数,因此您可以使用它将String映射到RolePermission(或任何您想要的对象),然后将结果收集到列表中。这样的事情对你有用吗?看起来你或多或少已经完成了String to RolePermission转换

final List<RolePermission> roles = getRoles().stream().map(roleString -> { <your conversion code> }).collect(Collectors.toList());