Java 8 lambda表达式或旧方式

huangapple go评论69阅读模式
英文:

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)

其中,ndeletePermissionDto.getPermissionId() 的大小,muserEntity.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 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&lt;Long&gt; ids = new HashSet&lt;&gt;(deletePermissionDto.getPermissionId());
userEntity.getPrivilegeEntities()
          .removeIf(x -&gt; ids.contains(x.getId()));

With score of O(n+m)

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

huangapple
  • 本文由 发表于 2020年9月2日 12:56:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/63698928.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定