英文:
Java 8 lambda expression or old way
问题
你好,我有关于Java 8的Lambda表达式的问题。例如,我想从类中删除以下id。
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;
}
}
}
类似于这段代码,可以使用Java 8中的Lambda表达式进行实现。
userEntity.getPrivilegeEntities().removeIf(i -> deletePermissionDto.getPermissionId().stream().anyMatch(permission_id -> i.getId().equals(permission_id)));
我想知道Java 8实现与第一段代码的渐近性。你认为哪种实现方式是最佳的呢?
英文:
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
得分: 4
你的第二种解决方案比第一种要快。
- 第一种是
O(n*m^2)
(如果能够正常工作的话。我怀疑如果你尝试删除除了最后一个权限以外的任何权限,应该会抛出IllegalStateException
) - 第二种是
O(n*m)
其中,n
是 deletePermissionDto.getPermissionId()
的大小,m
是 userEntity.getPrivilegeEntities()
的大小。
最佳解决方案如下:
HashSet<Long> ids = new HashSet<>(deletePermissionDto.getPermissionId());
userEntity.getPrivilegeEntities()
.removeIf(x -> ids.contains(x.getId()));
时间复杂度为 O(n+m)
附注:如果你对实际性能感兴趣,答案可能会有所不同。
英文:
Your second solution is faster than your first one.
- First is
O(n*m^2)
(If it works at all. I suspectIllegalStateException
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论