0

Hello guys I've got question about Java 8 lambda expression. For example I want to delete following id from class.

UserEntity userEntity = userEntityOptional.get();
for(Long permission_id : deletePermissionDto.getPermissionId())
{
    for(PrivilegeEntity p : userEntity.getPrivilegeEntities())
    {
        if(p.getId().equals(permission_id)){
            userEntity.getPrivilegeEntities().remove(p);
            break;
        }
    }
}

Similar to This code might be implemented in java 8 using a lambda expression.

userEntity.getPrivilegeEntities().removeIf(i -> deletePermissionDto.getPermissionId().stream().anyMatch(i.getId()::equals));

What I curious to know asymptotic of java 8 implementation of the same with the first block of code. And how do you think what the best way of implementation of this code.

1
  • 1
    This is a good question for discussion. But may be you have posted it to wrong forum :). As this forum is for question - answer only Commented Sep 2, 2020 at 5:14

1 Answer 1

4

Your second solution is faster than your first one.

  • First is O(n*m^2) (If it works at all. I suspect IllegalStateException should be thrown if you try to delete any but last permission)
  • Second is O(n*m)

Where n is size of deletePermissionDto.getPermissionId() and m is size of userEntity.getPrivilegeEntities().

Best solution would be:

HashSet<Long> ids = new HashSet<>(deletePermissionDto.getPermissionId());
userEntity.getPrivilegeEntities()
          .removeIf(x -> ids.contains(x.getId()));

With score of O(n+m)

PS: Answer will be different if you are interested in actual performance.

Sign up to request clarification or add additional context in comments.

2 Comments

You seem to assume a particular collection type for the result of userEntity.getPrivilegeEntities(). That’s fair, as the OP didn’t specify one, but you should should note which type you’re assuming. Likewise, copying deletePermissionDto.getPermissionId() into a HashSet is only necessary if it isn’t already a HashSet (I don’t know why the OP uses deletePermissionDto.getPermissionId().stream().anyMatch(i.getId()::equals) instead of just deletePermissionDto.getPermissionId().contains(i.getId()); I don’t know of any collection with a worse-than-linear contains).
@Holger Fair enough. If userEntity.getPrivilegeEntities() already HashSet there is no need in copying it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.