How to convert a list of strings into a list of objects?

Jose :

I have a list of roles in a database. They are of the form

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

So each role has an entry based on read/write permission. I want to convert the roles into a POJO which I can then send as JSON to a UI. Each POJO would have the role name, and a boolean for read or write permission.

Here is the RolePermission class:

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;
    }
}

I am doing the transformation like so:

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

Is there a way to do the foreach loop above using Java 8 streams?

This is a mock Backend instance that just returns a list of roles:

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

You can use groupingBy to join the different permissions for the same roleName together.

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;
}

I also think that your String.split was using an incorrect regex in the original post, because . is a special regex character. I've tested this and it works correctly.

Output:

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=470510&siteId=1