Skip to content

Java 8 lambda expression or old way

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

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.



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());
          .removeIf(x -> ids.contains(x.getId()));

With score of O(n+m)

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