找到数组的非相交元素的最佳方法

发布于 2025-02-07 17:39:39 字数 66 浏览 1 评论 0原文

我有2个用户对象。 1个数组包含所有用户的列表 第二个数组包含所有已记录用户的列表。 这是在用户中找到未遇到的最佳方法

I have 2 arrays of User Objects.
1 array contains list of all users
and 2nd array contains list of all logged in Users.
Which is the best way to find non-logged in users

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

命比纸薄 2025-02-14 17:39:39

有两种情况:

  1. 如果您没有用户中实现的平等和哈希代码方法:

最简单的方法是获取所有用户识别符,例如databaseID或用户名。将其持续到哈希结构中,以进行快速搜索。然后浏览所有用户,接受本集合中未包含的所有用户。

创建一组已记录的用户标识符:

 Set<Long> loggedUserIdentifiers = loggedUsers.stream()
                                   .map(User::getId) // I have chosen Id
                                   .collect(toSet());

现在您可以找到所有未燃烧的用户:

 List<User> unloggedUsers = allUsers.stream()
                            .filter( user -> !loggedUserIdentifiers.contains(user.getId()))
                            .collect(toSet());
  1. 如果您实现了平等和哈希代码,则可以简单地将所有记录的用户从所有用户集合的副本中删除。只需记住先创建一个副本,否则您只会以记录和未登录的用户结束。

      set&lt;用户&gt; AlluserCopy =新的Hashset&lt;&gt;(Allusers); //在列表上也有效
    AlluserCopy.RemoveAll(Loggedusers);
    设置&lt;用户&gt; notloggedusers = set.copyof(alluserCopy);
     

现在,您将拥有一个只有未记录的用户的集合。

There are two cases:

  1. If you do not have equals and hash code methods implemented in User:

then the simplest way would be to get all UserIdentifier, like databaseId or username. Persist it in a hashed structure, for fast search. Then go through all Users and accept all not contained in this collection.

Create a set of logged user Identifiers:

 Set<Long> loggedUserIdentifiers = loggedUsers.stream()
                                   .map(User::getId) // I have chosen Id
                                   .collect(toSet());

Now you can find all not-logged users:

 List<User> unloggedUsers = allUsers.stream()
                            .filter( user -> !loggedUserIdentifiers.contains(user.getId()))
                            .collect(toSet());
  1. If you have equals and hash code implemented, then you could simply remove all logged users from a copy of all Users collection. Just remember to create a copy first, otherwise You will end with only logged and not-logged Users.

    Set<User> allUserCopy = new HashSet<>(allUsers); // works on lists also
    allUserCopy.removeAll(loggedUsers);
    Set<User> notLoggedUsers = Set.copyOf(allUserCopy);
    

Now you will have a collection with only not logged users.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文