Reputation: 33
I want to convert an existing code to Lamda expression.
Map<Integer, List<Permission>> rpMap = new HashMap<>();
List<Integer> loginAccessCodes = loginAccessDao.getAuthorizedPermissions(loginId);
List<AccessCode> roles = roleDAO.getAllRoles();
for (AccessCode accessCode : roles) {
List<Permission> rolePermissions = rolePermissionDAO.getRolePermissions(accessCode.getAcCodeId());
for (Permission permission: rolePermissions) {
if (! loginAccessCodes.contains(permission.getPermId())) {
permission.setChecked(false);
permission.setGrayed(true);
}
}
rpMap.put(accessCode.getAcCodeId(), rolePermissions);
}
So far I have:
List<Permission> permissions = roles.stream()
.map(AccessCode -> rolePermissionDAO.getRolePermissions(AccessCode.getAcCodeId()))
.flatMap(rolePermissions -> rolePermissions.stream())
.filter(permission -> !loginAccessCodes.contains(permission.getPermId()))
.map(permission -> { permission.setChecked(false); permission.setGrayed(true); return permission; })
.collect(Collectors.toList());
Upvotes: 2
Views: 61
Reputation: 31878
A reason why it's not good to use streams(lambda expression) in your current context is that you end up modifying and object Permission
under certain filter
conditions to set few of its attributes.
Another thing that is not clear is the relation between the accessCode.getAcCodeId()
and permission.getPermId()
. Under the assumption that these two are equivalent, you could have expressed the iterative approach as:
Map<Integer, List<Permission>> rpMap = roles.stream()
.map(accessCode -> getRolePermissions(accessCode.getAcCodeId()))
.flatMap(Collection::stream)
.filter(permission -> !loginAccessCodes.contains(permission.getPermId()))
// following is what fails the purpose of using streams here
.map(permission -> {
permission.setChecked(false);
permission.setGrayed(true);
return permission;
})
.collect(Collectors.groupingBy(Permission::getPermId));
Also, if the relationship between those two ids
could be derived appropriately, you could further modify this approach to(do take note of the comments) :
Map<Integer, List<Permission>> rpMap = roles.stream()
// filter based on accessCode logic itself
.filter(accessCode -> !loginAccessCodes.contains(accessCode.getAcCodeId()))
// set the parameters within function called inside 'map'
.map(accessCode -> getRolePermissionsWithFlagsSet(accessCode.getAcCodeId()))
.flatMap(Collection::stream) // flat it to Stream<Permission>
.collect(Collectors.groupingBy(Permission::getPermId)); // group it using the 'id' (Integer)
Upvotes: 1