gpt4 book ai didi

Java 哈希集搜索

转载 作者:行者123 更新时间:2023-12-02 00:41:31 25 4
gpt4 key购买 nike

下午好

在Java中,我有HashSet,其中包含具有属性的对象User列表:

  • 电子邮件
  • 群组
  • 机器名称

现在我的哈希集具有以下值(上述对象的列表)

email            | group   | machinename
----------------------------------------
robert@yahoo.com | hewitt | AP1
Mathew@gmail.com | test | AP1
melody@app.com | test | AP1
nick@ac.co | test | AP1
robert@yahoo.com | project | AP1
nick@ac.co | project | AP1

现在我必须找到那些具有相同电子邮件和计算机但组名称不同的记录,在上面的情况下是:

nick@ac.co (which has "project" and "test" group)
robert@yahoo.com (which has "hewitt" and "test" groups)

如何使用 java 代码找到它?

最佳答案

这将完全满足您的要求:

Set<User> users = new HashSet<User>();
// ...

Map<String, List<User>> hits = new HashMap<String, List<User>>();

for (User user : users) {
String key = user.getMachineName() + user.getEmail();
List<User> list = hits.get(key);
if (list == null) {
list = new ArrayList<User>();
hits.put(key, list);
}
list.add(user);
}

// Users are now grouped by their "machine name + email" as a single key

for (Map.Entry<String, List<User>> hit : hits.entrySet()) {
if (hit.getValue().size() < 2) continue;
System.out.println("These users share the same email and machine name: "
+ hit.getValue()); // hit.getValue() is an ArrayList<User>
}

关于Java 哈希集搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6237425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com